I am in the middle of refining a rather large bit of code. Alot of it contains many general warnings and notices which do not affect the execution of the code (ie: undefined varilables, or array keys without qoutes).
I want to write a function which allows me to concentrate on the fatal errors first and then I will open it up to the less urgent warnings and notices. I found this code, but it emails every little warning notice and error.
http://net.tutsplus.com/tutorials/php/quick-tip-email-error-logs-to-yourself-with-php/
How can I modify this code so it only deals with things like:
You can "catch" these "fatal" errors by using set_error_handler() and checking for E_RECOVERABLE_ERROR. I find it useful to throw an Exception when this error is caught, then you can use try/catch.
Fatal errors are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.
There are three (3) types of fatal errors: Startup fatal error (when the system can't run the code at installation) Compile time fatal error (when a programmer tries to use nonexistent data) Runtime fatal error (happens while the program is running, causing the code to stop working completely)
set_error_handler
allows you to specify a user-defined error handling function for deciding what to do with certain (but only non-fatal) errors. You can then handle specific types of errors in any fashion you deem necessary, for example notifying a system administrator via email, or saving to a specific log file. See: PHP Doc for further details.
With regards to your request you could the following approach:
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting
return;
}
switch ($errno) {
case E_USER_ERROR:
case E_ERROR:
case E_COMPILE_ERROR:
echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
echo " Fatal error on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
echo "Aborting...<br />\n";
emailErrorFunction($errno,$erstr,$errfile,$errline);
exit(1);
break;
default:
echo "Unknown error type: [$errno] $errstr<br />\n";
break;
}
/* Don't execute PHP internal error handler */
return true;
}
// Report all errors
error_reporting(E_ALL);
// User a custom error handler to print output
set_error_handler( 'myErrorHandler' );
As that error-handling does not work for Fatal Errors (Parse errors, undefined functions etc.), you need to tape this with register_shutdown_function
as outlined in a related question:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With