Insomanic: Andy Young's Blog

  • Archive
  • RSS

PHP Trick: Catching fatal errors (E_ERROR) with a custom error handler

Implementing a custom error handler using set_error_handler() in PHP can be a useful technique (Google search for more info/examples)

Unfortunately, set_error_handler() doesn’t catch fatal errors - as the PHP docs say:

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

Handily, I just discovered it’s possible to catch fatal E_ERROR errors and direct them to your custom error handler using a combination of register_shutdown_function() and error_get_last():

set_error_handler('myErrorHandler');
register_shutdown_function('fatalErrorShutdownHandler');

function myErrorHandler($code, $message, $file, $line) {
  ...
}

function fatalErrorShutdownHandler()
{
  $last_error = error_get_last();
  if ($last_error['type'] === E_ERROR) {
    // fatal error
    myErrorHandler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
  }
}

The key is that functions registered with register_shutdown_function() are called even on a fatal error - including out of memory errors. error_get_last() can then be used to detect whether we’re ending the script because of a fatal error, and pass the error info to your custom error handler if so.

    • #Dev
    • #php
  • 2 years ago
  • 1
  • Comments
  • Permalink
  • Share
    Tweet

1 Notes/ Hide

  1. kothvosta liked this
  2. apexa posted this

Recent comments

Blog comments powered by Disqus
← Previous • Next →

About

Avatar Hi, I'm Andy. I'm an entrepreneur, a techie, a founder, a CTO, a music addict. I'm working on my startup GroupSpaces - solving the pains of membership and group management. I created Selective Tweets (the #fb hashtag). I live and work in London.

Me, Elsewhere

  • @andyy on Twitter
  • Facebook Profile
  • andyjy on Delicious
  • Google
  • Linkedin Profile
  • andyyoung on github
  • RSS
  • Random
  • Archive
  • Mobile

Copyright (c) 2009-2012 AY.. Effector Theme by Carlo Franco.

Powered by Tumblr