Eli : Memcached, MySQL, Highcharts

Handling fatal error in PHP with register_shutdown_function

PHP 5.2.0 bring us a new function : error_get_last()

It return an associative array describing the last error with keys "type", "message", "file" and "line" about the last error that occurred.

We can now use it with register_shutdown_function to handle fatal error, log, redirect, html page, instead of the infamous white page.

/**
 * Handling fatal error
 *
 * @return void
 */
function fatalErrorHandler()
{
    # Getting last error
    $error = error_get_last();
 
    # Checking if last error is a fatal error 
    if(($error['type'] === E_ERROR) || ($error['type'] === E_USER_ERROR))
    {
         # Here we handle the error, displaying HTML, logging, ...
         echo 'Sorry, a serious error has occured in ' . $error['file'];
    }
}
 
# Registering shutdown function
register_shutdown_function('fatalErrorHandler');

Resources :

  • http://www.php.net/manual/en/function.error-get-last.php
  • http://php.net/manual/en/errorfunc.constants.php

Related Posts





comments powered by Disqus

You may also be interested in