You are seeing » PHP » How to catch PHP errors

How to catch PHP errors

2011/04/18

When you are developing an application some things can goes wrong in your code, for example, a non declared function or class, out of memory and so on.

Even that you are using a test unit, some kind of erros only will occur in production enviroment.

PHP has two function to manipulate error are:

set_error_handler()
and
set_exception_handler()

But, this functions works only in some cenarios, if your code get an E_ERROR or E_PARSE error, you can't catch it.

On the other hand, we can use register_shutdown_function() to catch E_ERROR or E_PARSE error too.

See this piece of code:

<?
/* considering that in production enviroment is recommended don't show errors, it is a default settings in php.ini. */
ini_set('display_errors', 'Off');

register_shutdown_function(create_function('','
    if ( ($error = error_get_last()) ) {
        // do something what you need, like:
        // send email alert about error;
        // write/log error to a file;
        // show or redirect the user to a customized error
page.
        echo "Oops, I get a error.<hr/>";
        print_r($error);
    }
'));
?>


This code is really useful to catch many errors and alert you or developing team about something non expected in you PHP application.




Name : Email :