PHP Error Handler

If your Slim Framework application throws aPHP Runtime error (PHP 7+ only),the application invokes its PHP Error handler and returns aHTTP/1.1 500 Internal Server Error response to the HTTP client.

Please note that Warnings and Notices are not caught by default. If you wish your application to display an error page when they happen, you have to run the following code before the app starts. In most cases that means adding it to the very top of index.php.

  1. <?php
  2. error_reporting(E_ALL);
  3. set_error_handler(function ($severity, $message, $file, $line) {
  4. if (error_reporting() & $severity) {
  5. throw new \ErrorException($message, 0, $severity, $file, $line);
  6. }
  7. });

This way all Warnings and Notices will be treated as Errors and as such will trigger the defined handlers.

Default PHP Error handler

Each Slim Framework application has a default PHP Error handler. This handlersets the Response status to 500, it sets the content type to text/html,and it writes a simple explanation to the Response body.

Custom PHP Error handler

A Slim Framework application’s PHP Error handler is a Pimple service. You cansubstitute your own PHP Error handler by defining a custom Pimple factorymethod with the application container.

  1. // Create Slim
  2. $app = new \Slim\App();
  3. // get the app's di-container
  4. $c = $app->getContainer();
  5. $c['phpErrorHandler'] = function ($c) {
  6. return function ($request, $response, $error) use ($c) {
  7. return $response->withStatus(500)
  8. ->withHeader('Content-Type', 'text/html')
  9. ->write('Something went wrong!');
  10. };
  11. };

N.B Check out Not Found docs forpre-slim creation method using a new instance of \Slim\Container

In this example, we define a new phpErrorHandler factory that returns acallable. The returned callable accepts three arguments:

  • A \Psr\Http\Message\ServerRequestInterface instance
  • A \Psr\Http\Message\ResponseInterface instance
  • A \Throwable instanceThe callable MUST return a new \Psr\Http\Message\ResponseInterfaceinstance as is appropriate for the given error.