Tuesday, 11 September 2018

Replace error reporting with exception handlers with PHP

As part of a series of posts about PHP exception handling, this post looks at how to make regular errors use exception model. Normally only the newer object-oriented extensions throw exceptions but it is possible to make all errors throw an exception instead using set_error_handler.

Normal behavior

The normal behavior for a normal error is to show an error message which cannot be handled by the try...catch syntax. For example, if error reporting is E_ALL and we try to access a variable which has not yet been set:
error_reporting(E_ALL);
echo $x;
This is what will be displayed:
Notice: Undefined variable: x in [filename] on line [line number]

Bind errors to the ErrorException handler

Instead of this default error behavior, errors can be bound to the ErrorException handler like so:
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
What this is doing is replacing the default error handler with our own function which in turn throws an ErrorException. Now when we try to use the same variable above that has not been set an exception will be thrown, looking something like this:
Fatal error: Uncaught exception 'ErrorException' with message 'Undefined variable: x' in [filename]:[line number]
Stack trace:
#0 [filename]([line number]): exception_error_handler()
#1 {main}
  thrown in [filename] on line [line number]
This could now instead be handled inside a try..catch block like so:
try {
    echo $x;
}
catch(Exception $e) {
   
}
Obviously you wouldn't be trying to catch such a trivial exception example; it's just to illustrate the other examples on this page which deal with a fairly trivial error. You could then potentially use an exception handler to deal with these sorts of exceptions, instead of having to have separate error handlers and exception handlers.

Exception Series

This is the fourth post in a weekly series of six about PHP exceptions. Read the previous post "Catch uncaught exceptions with PHP", the next post "Extend PHP's exception object" and use the links below to subscribe to my RSS feed, by email, or follow me on Twitter or Facebook to keep up to date with my daily postings.

Related posts:

0 comments:

Post a Comment