Exception_DefaultHandler, an exception handler for PHP5+

Exception_DefaultHandler is a low-overhead, use-anywhere class to act as, as the name suggests, a default (fallback) exception handler for your PHP 5+ applications. Normally, if some code encounters an error or exception in PHP and it’s not explicitly caught, PHP will terminate the application and either display an error on screen (terrible on a production site), or log to the server error log/a file. In both cases, your chance to get to the root cause of the problem is limited. Exception_DefaultHandler gives you both improved debugging output in a development environment, and root-cause analysis in a production one. Key features include:

  • Can handle both PHP 5-style exceptions and older-style errors (trigger_error() style, which includes errors thrown by most core PHP modules)
  • Creates full backtraces (including function parameters) and can handle in several ways:
    • display to screen (development only!)
    • send by e-mail
    • log to file
  • Creates a unique error code for each distinct fault (based on the code path), which you can use to de-duplicate
  • Rate limiting for e-mailed error reports
  • Displays a friendlier error page in a production environment
  • Respects, and works with, your normal PHP settings: error_reporting, display_errors and log_errors. Defaults to using your Apache ServerAdministrator for e-mailed error reports, where relevant
  • Works on the CLI and tries to intelligently output in HTML or text dependent on environment
  • Handles errors from non-interactive requests (AJAX/DAV) in a special way, where possible
  • Provides a simple function (handleExceptionManual()) to pass higher-level exceptions down to, if you are already handling them but want to take advantage of Exception_DefaultHandler’s reporting functionality.

Using it is as simple as adding the following code to somewhere in your code that gets executed (early) in every request, i.e. a bootstrap file or front controller:

require_once 'Exception/DefaultHandler.php'
set_exception_handler(array('Exception_DefaultHandler','handleException'));
set_error_handler(array('Exception_DefaultHandler','handleError'));

The easiest way to install is from the pear.timj.co.uk PEAR channel:

pear channel-discover pear.timj.co.uk
pear install timj/exception_defaulthandler

A full list of releases is also available on the PEAR server.

Source code is in the Exception_DefaultHandler SVN repository.