Throwing exceptions on PHP errors

I have this code running on my site:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);


Which was taken from the PHP manual.

Unfortunately, it seems to completely ignore my error handling settings, throwing exceptions on E_NOTICE warnings such as undefined index. I don’t want my application to go down just because I use an array without checking if an index is defined first. I don’t consider the code below to be incorrect in any way:

$current_url = $_GET['current_url'] ? $_GET['current_url'] : '/'; // throws undefined index 'current_url' exception

Does anyone have experience with using exceptions as an error handler, and how to prevent the above scenario?

Well, I find that it’s not always the easiest way to do it, often I find that an error further down the chain will give a better explanation of what caused the problem and make it quicker to track down than having to follow the stack trace. YMMV of course.

Really? With an exception, you get a stack trace. So you can deduct exactly which path the code took to end up at the error. I much prefer that over an error-log.

From personal experience, I’d advise against set_error_handler throwing exceptions for warnings and notices. Quite often, it’s useful to see the chain of errors. “Undefined index” errors stopping page execution is not helpful for debugging at all… especially when they’re in methods used many times within the page.

Alternatively, you can check for the error level in the handler. This works for error-suppression as well:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
  // check if error is suppressed
  if (error_reporting() == 0) {
  // check if severity matches error_reporting level
  if (error_reporting() & $errno) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);

Never mind-- I found the answer here:

set_error_handler takes a second optional parameter to determine what errors to use exceptions for.

That’ll teach me to copy+paste a function without reading its documentation :slight_smile: