Automatic errors reporting in PHP
February 15, 2009 — Florent ClairambaultPHP has a pretty interesting feature, you can define a callback method to “catch” any error “thrown” in your code. And I’m sure most of you don’t use it. It’s really usefull when you want to make sure to detect error before any user reports it (which can takes time). This is all about avoiding to demolish with some lame errors your “user experience”.
I now use it in each of my index.php pages (which generally loads every other pages), but to speeds things up I make it load the actual method only when the error is “catched”.
This is the code :
1 2 3 4 5 | function lightErrorHandler($errno, $errstr, $errfile, $errline) { require_once('./include/functions/errorHandler.inc.php'); return errorHandler($errno, $errstr, $errfile, $errline); } set_error_handler( 'lightErrorHandler', E_ALL ^ E_NOTICE); |
This is the actual error-management code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function errorHandler($errno, $errstr, $errfile, $errline) { $tab = array( 'no' => $errno, 'str' => $errstr, 'file' => $errfile, 'line' => $errline ); $message = 'This error happened :'."\n\n". 'Error : '."\n".print_r( $tab, true )."\n\n". 'StackTrace : '."\n".print_r( debug_backtrace(), true )."\n\n"; //'Globals : '."\n".print_r( $GLOBALS, true )."\n\n"; file_put_contents( '/tmp/error'.str_replace('/','_', $errfile ).'_'.$errline, $message ); mail( 'yourmail@host.com', 'Error report : '.$errfile.':'.$errline, $message ); } |
debug_backtrace requires PHP 4.3 and set_error_handler only supports error types since PHP 5.0. So, if you plan on using this on a PHP 4.X host, you have to make sure your code doesn’t throw E_NOTICE errors. My code is never E_NOTICE error safe, because this slows down PHP programming and PHP execution.
loading...