Hello,
In slim v4, How can I invoke a 404 Not Found Exception?
More details: if I use:
throw new \Slim\Exception\HttpNotFoundException($request);
It show me Fatal Error, and doesn’t trigger the default 404 slim event.
You will only get a fatal error if you don’t register the Slim ErrorMiddleware:
$app->addErrorMiddleware(true, true, true);
You could also define a custom error handler for the \Slim\Exception\HttpNotFoundException::class
.
Example:
$errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, $logErrors, $logErrorDetails);
$errorMiddleware->setErrorHandler(\Slim\Exception\HttpNotFoundException::class, function (
\Psr\Http\Message\ServerRequestInterface $request,
\Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
) {
$response = new \Slim\Psr7\Response();
$response->getBody()->write('My custom 404 error');
return $response->withStatus(404);
});
You custom error handler could also be a class with a __invoke()
method.
To trigger the 404 error handler just throw a HttpNotFoundException.
throw new \Slim\Exception\HttpNotFoundException($request);
Or you just register a custom default error handler to handle the HttpNotFoundException.
// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
$errorMiddleware->setDefaultErrorHandler($customErrorHandler);
http://www.slimframework.com/docs/v4/middleware/error-handling.html
1 Like
Thanks for your reply