Database error handling with the Zend Framework
Posted May 11th, 2008 in PHP
When running database queries in the past, I have used my own database abstraction libraries, Code Igniter, the PEAR database library, ADODB and ADODB Lite. Each of these easily allows error handling by having a function called in the event of a database error occuring. I have recently started using the Zend Framework, but there doesn't appear to be this capability of automatic error handling. This short post looks at how to capture and handle database errors with the Zend Framework.
Basically, you need to put your database queries inside a try...catch block and in the catch block call your error handling function. This is easy enough but you have to remember to do it each time, whereas using the other database libraries there were hooks to call a user defined function in the event of an error so you didn't need to remember to invoke it each time.
So, with the Zend Framework you need to do something like this each time you call a database query:
try {
...
// code to run a database query etc here
...
}
catch Exception $e {
my_error_handler($e);
}
Then your error handling function could log the error to a file, display an error to the user and/or send you an email etc. You can get the message from the exception object with the ->getMessage() function.
Subscribe!
If you found this post interesting and would like to be notified the next time something is posted, please subscribe to my RSS Feed. Thanks for visiting!

