System Error Handler
The default error handler is very basic. It sets the Response status code to , it sets the Response content type to text/html
, and appends a generic error message into the Response body.
This is probably not appropriate for production applications. You are strongly encouraged to implement your own Slim application error handler.
The default error handler can also include detailed error diagnostic information. To enable this you need to set the displayErrorDetails
setting to true:
Custom error handler
There are two ways to inject handlers:
$c = new \Slim\Container();
$c['errorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
->withHeader('Content-Type', 'text/html')
->write('Something went wrong!');
};
};
In this example, we define a new errorHandler
factory that returns a callable. The returned callable accepts three arguments:
- A
\Psr\Http\Message\ServerRequestInterface
instance - A
\Psr\Http\Message\ResponseInterface
instance - A
\Exception
instanceThe callable MUST return a new\Psr\Http\Message\ResponseInterface
instance as is appropriate for the given exception.
Error handlers may also be defined as an invokable class.
class CustomHandler {
public function __invoke($request, $response, $exception) {
->withStatus(500)
->withHeader('Content-Type', 'text/html')
}
}
This allows us to define more sophisticated handlers or extend/override thebuilt-in Slim\Handlers*
classes.
Please note: The following four types of exceptions will not be handled by a custom errorHandler
:
Slim\Exception\MethodNotAllowedException
: This can be handled via a custom .Slim\Exception\NotFoundException
: This can be handled via a customnotFoundHandler
.- Runtime PHP errors (PHP 7+ only): This can be handled via a custom .
Slim\Exception\SlimException
: This type of exception is internal to Slim, and its handling cannot be overridden.
To completely disable Slim’s error handling, simply remove the error handler from the container: