Exception Error Handlers

Exception Error Handlers are error handlers that throw predefined exceptions in response to PHP errors. The Error Library provides ExceptionErrorHandler class to easily create exception-throwing error handlers.

A simple example with ExceptionErrorHandler

In this example we’ll set up a context to throw \ErrorException in response to PHP errors of severity E_USER_ERROR. We’ll use following two functions

1
2
use function Korowai\Lib\Context\with;
use function Korowai\Lib\Error\exceptionErrorHandler;

The exceptionErrorHandler() returns new error handler which throws a predefined exception. This handler may be enabled for a context by passing it as an argument to with(). All the necessary code is shown in the following snippet

1
2
3
4
5
6
7
8
try {
    with(exceptionErrorHandler(\ErrorException::class))(function ($eh) {
        @trigger_error('boom!', E_USER_ERROR);
    });
} catch (\ErrorException $e) {
    fprintf(STDERR, "%s:%d:ErrorException:%s\n", basename($e->getFile()), $e->getLine(), $e->getMessage());
    exit(1);
}

The output from our example is like

  • stderr

    simple_exception_thrower.php:11:ErrorException:boom!