Error Handling

Sooner or later every application has to deal with error conditions and programming mistakes. Unless something is considered a really serious problem, PHP simply emits a warning message, and then goes on as if nothing happened. Back in the days, when PHP code was embedded into HTML documents, this lax way of handling errors was considered a feature, an explicit design choice when creating PHP as a language. In a modern, object-oriented PHP application, where an explicit handling of all error conditions is preferred, such behavior is rather counterproductive.

To fix this and to handle errors in an object-oriented way with PHP 5.6 and earlier a custom error handler had to be registered, converting errors into exceptions. For example by using the built-in ErrorException class:

set_error_handler(
    function($errno, $errstr, $errfile, $errline, array $errcontext)
    {
        throw new ErrorException(
            $errstr, 0, $errno, $errfile, $errline
        );
    }
);

The error handler shown above will transform every error into an exception which can then be conveniently caught and handled by the calling code.

The fifth parameter $errcontext – which contains a list of all local variables available at the error location – is not used and could be omitted in the function declaration. Starting with PHP 7.2, it is deprecated and should no longer be used. In contrast to other deprecated functionality, though, this will not trigger the usual notice as this would cause an endless chain of invocations of the registered error handler.

Sadly, this approach does not work for all error types. Some error types are considered more serious and do not trigger the registered error handler. While PHP 5.6 does not provide a way to recover from things like parsing errors, registering a shutdown handler at least provided a means to a controlled shutdown.

Luckily, with PHP 7 all this changed fundamentally.