Catching uncaught exceptions via set_error_handler

I am trying to work out a custom error handler to catch uncaught exceptions, but can’t seem to figure out how to do it. php.net’s example doesn’t catch uncaught exceptions, just the contents of trigger_error() it seems. The goal I have in mind is to throw certain exceptions that I can catch all in one place - the set_error_handler function. Then, for some exceptions, I will stop the program, and for others I may resume it.

Here’s some code - I am not sure if this is the correct start at all, and it’s fine to throw it out entirely. A lot of it I adapted from code found here and there.



function error_handler($errno, $errstr, $errfile, $errline)
	switch ($errno)
	{
		case E_USER_ERROR:
			// log error
                        echo 'user error found';
			break;
		case E_WARNING:
                       echo 'warning error found';
                       break;
		case E_USER_WARNING:
			echo 'e_usererror found';
                        break;
		case E_NOTICE:
                      echo 'e_notice error found';
                      break;
		case E_USER_NOTICE:
			echo 'user error found';
			break;
		default:
			echo 'default error reached';
			break;

	}
	return true;
}

set_error_handler('error_handler');

class MathException extends Exception {}


$x = 1;
$y = 2;
	
if (x != $y)
{
	throw new MathException('x not equal to y');
}


To specify my problem, I do not know how to catch MathException (via set_error_handler), and I do not know how to extract info from it once it is caught. Currently I just receive a fatal error of uncaught exception with no indication it was every caught or handled in any way.

Wrap things in a try / catch block.

To extract the error messages, use:

// Line number error occured on
$this->getLine()

// File
$this->getFile()

// Error message
$this->getMessage()

I am trying specifically not to use a try\catch block, and catch with set_error_handler, so I only catch errors in client code that I want to catch, rather than having to catch all of them.

To act on uncaught exceptions you need to use set_exception_handler()

The method should have 1 parameter (the said exception), you can then user $ex->getMessage() to get the error message.
Not that, unlike with set_error_handler(), you don’t need to call ‘die()’ to stop the script as the script will be stopped after the call of your custom exception handler.
And, not that if you execute a lot of code in your custom exception handler, if an error is raised, you’ll get a message like ‘uncaught exception with unknown stack frame’… So, if you do a lot of stuff in it, you need to use a try…catch in your custom function.

Thank you, that was what I was looking for. I didn’t realize there was a separate function for handling exceptions rather than errors. I didn’t realize there was a difference.
Your blog post in your signature was helpful, too.