In today's video quick tip, we'll review the process of setting custom error handlers with PHP. Along the way, we'll also learn how to log and email those potential errors to ourselves. That way, even when your web application has been deployed, you'll be the first to know when an error is encountered.
Intro
Source
<?php // Our custom error handler function nettuts_error_handler($number, $message, $file, $line, $vars) { $email = " <p>An error ($number) occurred on line <strong>$line</strong> and in the <strong>file: $file.</strong> <p> $message </p>"; $email .= "<pre>" . print_r($vars, 1) . "</pre>"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Email the error to someone... error_log($email, 1, '[email protected]', $headers); // Make sure that you decide how to respond to errors (on the user's side) // Either echo an error message, or kill the entire project. Up to you... // The code below ensures that we only "die" if the error was more than // just a NOTICE. if ( ($number !== E_NOTICE) && ($number < 2048) ) { die("There was an error. Please try again later."); } } // We should use our custom function to handle errors. set_error_handler('nettuts_error_handler'); // Trigger an error... (var doesn't exist) echo $somevarthatdoesnotexist;
Conclusion
If you decide to set your own error handlers, make sure that you:
- Determine whether or not to
die()
and kill the page. - Provide some level of feedback for the user. If there was a fatal error, let them know in some form!
- You don't want to email yourself errors when debugging. You can create a
$debug
variable that, if set totrue
, we'll bypass the process of emailing you the error, and will, instead, echo the error onto the page. If you need a code snippet for this, just let us know!
Comments