6

I am attempting to try to do something useful with PDO exceptions other than display them, but I cannot find for the life of me how to use an error handler (set_error_handler) or anything custom to deal with PDOs exceptions.

Now I am using try..catch blocks of course the catch the exception, do I implement a custom error handler in the catch part, or can I skip the try->catch block completely as the exception handler would handle it for me (by calling or throw new exception (...) on the statement?

I guess what I am asking is an example to catch PDO exceptions and log them more or less (any simple code correct or not I can use, I'm not TOO dumb).

1
  • 1
    Heh.. when googling set_error_handler pdo this comes up first page.. Odd it's not talked about much. Commented Oct 6, 2010 at 17:37

1 Answer 1

10

You'll have to use a try..catch block around each PDO query. Add your log function in the catch part. There is no generic handler for exceptions in PHP.

try {  
   pdo::error();  
}  
catch (Exception $e) {  
   syslog($e);  
}  

If you want to avoid the try..catch blocks you can however configure PDO to only show errors instead of throwing exceptions. http://php.net/manual/en/pdo.error-handling.php

 $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome, I can just use error handler then (I found a really nice function to log errors to disk).
Your default set_error_handler() will see all PDO warnings, just like any other errors.
Accepted gladly, I decided to just leave it to PHP's own error handling with this (display errors off, log_errors on for ease of implementation). Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.