Custom Error Handlers¶
With The Error Library and Contexts you can
easily use your own functions as error handlers for particular calls. A class
named ErrorHandler
serves the purpose.
Simple example with custom error handler¶
The example uses the following symbols
1 2 | use function Korowai\Lib\Context\with;
use function Korowai\Lib\Error\errorHandler;
|
Our error handler will respond differently to user warnings and notices. Warnings will be printed to stderr, while notices will go normally to stdout.
1 2 3 4 5 6 7 8 9 | function watch(int $severity, string $message, string $file, int $line) : bool
{
if ($severity & (E_USER_WARNING|E_USER_ERROR)) {
fprintf(STDERR, "beware, %s!\n", $message);
} else {
fprintf(STDOUT, "be cool, %s\n", $message);
}
return true;
}
|
The ErrorHandler
object is used to enable
our error handler temporarily, so it is active only within the context
1 2 3 4 5 | with(errorHandler(watch::class))(function ($eh) {
@trigger_error('the weather is nice', E_USER_NOTICE);
@trigger_error('rain is coming', E_USER_WARNING);
});
@trigger_error('good night', E_USER_NOTICE);
|
The outputs from the above example are
- stdout:
1 | be cool, the weather is nice
|
- stderr:
1 | beware, rain is coming!
|
Note, that the last call to @trigger_error()
(line 5) didn’t output
anything.