Slim 3 registers two error handers:
- errorHandler to trap PHP Exceptions
- phpErrorHandler to trap PHP 7 Errors
This means that if you want to override the default error handlers, you need to override both error handlers with your own code.
Each error handler is a callable. The signatures are:
- errorHandler: function ($request, $response, $exception)
- phpErrorHandler: function ($request, $response, $error)
To override a error handler, simply register a new callable with the Container:
$container = $app->getContainer();
$container['errorHandler'] = function ($container) {
return function ($request, $response, $exception) use ($container) {
// retrieve logger from $container here and log the error
$response->getBody()->rewind();
return $response->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write("Oops, something's gone wrong!");
};
};
$container['phpErrorHandler'] = function ($container) {
return function ($request, $response, $error) use ($container) {
// retrieve logger from $container here and log the error
$response->getBody()->rewind();
return $response->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write("Oops, something's gone wrong!");
};
};
If you don't want to repeat yourself, you can register the `phpErrorHandler` like this:
$container['phpErrorHandler'] = function ($container) {
return $container['errorHandler'];
};
Note that you can register any PHP callable, so a class with an __invoke() method also works.
Handling PHP notices
As an aside, Slim 2's error handler catches PHP notices for you (which can be infuriating or very useful!). Slim 3 doesn't do this by default, so if you want to catch PHP notices then you need to register your own error handler like this:
set_error_handler(function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// This error code is not included in error_reporting, so ignore it
return;
}
throw new \ErrorException($message, 0, $severity, $file, $line);
});
That's all there is to it.