404 Not Found Handler
Если ваше приложение Slim Framework не имеет маршрута, соответствующего текущему URI-запросу HTTP, приложение вызывает обработчик Not Found и возвращает HTTP/1.1 404 Not Found ответ HTTP-клиенту.
Обработчик по умолчанию Not Found
Each Slim Framework application has a default Not Found handler. This handler sets the Response status to 404 , it sets the content type to text/html , and it writes a simple explanation to the Response body.
Пользовательский обработчик Not Found
Обработчик Not Found для Slim Framework — это услуга Pimple. Вы можете заменить свой собственный обработчик Not Found, указав собственный заводский метод Pimple с контейнером приложения.
$c = new \Slim\Container(); //Create Your container //Override the default Not Found Handler $c['notFoundHandler'] = function ($c) < return function ($request, $response) use ($c) < return $c['response'] ->withStatus(404) ->withHeader('Content-Type', 'text/html') ->write('Page not found'); >; >; //Create Slim $app = new \Slim\App($c); //. Your code
В этом примере мы определяем новый notFoundHandler фабрику, который возвращает вызываемый. Возвращаемый вызов допускает два аргумента:
- \Psr\Http\Message\ServerRequestInterface экземпляр
- \Psr\Http\Message\ResponseInterface экземпляр
Вызываемый ДОЛЖЕН вернуть соответствующий \Psr\Http\Message\ResponseInterface экземпляр.
404 Not Found Handler
If your Slim Framework application does not have a route that matches the current HTTP request URI, the application invokes it’s Not Found handler and returns a HTTP/1.1 404 Not Found response to the HTTP client.
Default Not Found handler
Each Slim Framework application has a default Not Found handler. This handler sets the Response status to 404 , it sets the content type to text/html , and it writes a simple explanation to the Response body.
Custom Not Found handler
A Slim Framework application’s Not Found handler is a Pimple service. You can substitute your own Not Found handler by defining a custom Pimple factory method with the application container before you instantiate the App object.
$c = new \Slim\Container(); //Create Your container //Override the default Not Found Handler before creating App $c['notFoundHandler'] = function ($c) return function ($request, $response) use ($c) return $response->withStatus(404) ->withHeader('Content-Type', 'text/html') ->write('Page not found'); >; >; //Create Slim $app = new \Slim\App($c); //. Your code
In this example, we define a new notFoundHandler factory that returns a callable. The returned callable accepts two arguments:
- A \Psr\Http\Message\ServerRequestInterface instance
- A \Psr\Http\Message\ResponseInterface instance
The callable MUST return an appropriate \Psr\Http\Message\ResponseInterface instance.
If you wish to override the default Not Found handler after you instantiate the App object you can unset the default handler then overwrite it.
$c = new \Slim\Container(); //Create Your container //Create Slim $app = new \Slim\App($c); //. Your code //Override the default Not Found Handler after App unset($app->getContainer()['notFoundHandler']); $app->getContainer()['notFoundHandler'] = function ($c) return function ($request, $response) use ($c) $response = new \Slim\Http\Response(404); return $response->write("Page not found"); >; >;
System Error Handler
Things go wrong. You can’t predict errors, but you can anticipate them. Each Slim Framework application has an error handler that receives all uncaught PHP exceptions. This error handler also receives the current HTTP request and response objects, too. The error handler must prepare and return an appropriate Response object to be returned to the HTTP client.
Default error handler
The default error handler is very basic. It sets the Response status code to 500 , 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:
$configuration = [ 'settings' => [ 'displayErrorDetails' => true, ], ]; $c = new \Slim\Container($configuration); $app = new \Slim\App($c);
Custom error handler
A Slim Framework application’s error handler is a Pimple service. You can substitute your own error handler by defining a custom Pimple factory method with the application container.
There are two ways to inject handlers:
Pre App
$c = new \Slim\Container(); $c['errorHandler'] = function ($c) return function ($request, $response, $exception) use ($c) return $response->withStatus(500) ->withHeader('Content-Type', 'text/html') ->write('Something went wrong!'); >; >; $app = new \Slim\App($c);
Post App
$app = new \Slim\App(); $c = $app->getContainer(); $c['errorHandler'] = function ($c) return function ($request, $response, $exception) use ($c) return $response->withStatus(500) ->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 instance
The callable MUST return a new \Psr\Http\Message\ResponseInterface instance as is appropriate for the given exception.
Class-based error handler
Error handlers may also be defined as an invokable class.
class CustomHandler public function __invoke($request, $response, $exception) return $response ->withStatus(500) ->withHeader('Content-Type', 'text/html') ->write('Something went wrong!'); > >
$app = new \Slim\App(); $c = $app->getContainer(); $c['errorHandler'] = function ($c) return new CustomHandler(); >;
This allows us to define more sophisticated handlers or extend/override the built-in Slim\Handlers\* classes.
Handling other errors
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 notAllowedHandler .
- Slim\Exception\NotFoundException : This can be handled via a custom notFoundHandler .
- Runtime PHP errors (PHP 7+ only): This can be handled via a custom phpErrorHandler .
- Slim\Exception\SlimException : This type of exception is internal to Slim, and its handling cannot be overridden.
Disabling
To completely disable Slim’s error handling, simply remove the error handler from the container:
unset($app->getContainer()['errorHandler']); unset($app->getContainer()['phpErrorHandler']);
You are now responsible for handling any exceptions that occur in your application as they will not be handled by Slim.