I want to create a Slim 4 compatible custom error page /JSON reply that is returned, when a non-existing route is request.
Default route (Slim 3)
I've recently upgraded from Slim 3 to Slim 4. With Slim 3, I had a default route that perfectly did the job:
$app->any('/[{path:.*}]', function (Request $request, Response $response, array $args) {
// catching any other requests...
/* ... creating JSON error object and write it to $slimresponse ... */
return ($slimresponse);
});
However, when I do this in Slim 4, I get an error
Type: FastRoute\BadRouteException
Code: 0
Message: Cannot register two routes matching "/" for method "GET"
This obviouosly means that Slim recognizes this as double entry for GET /, which is disallowed in Slim 4.
This article also provided no help for Slim 4, unfortunately.
notFound
Furthermore, according to https://www.javaer101.com/en/article/13830039.html, I've tried to add
$app->notFound(function () use ($app) {
$app->response->setStatus(403);
echo "Forbidden";
//output 'access denied', redirect to login page or whatever you want to do.
});
to my routes.php, but it doesn't work:
Call to undefined method Slim\App::notFound()
HttpNotFoundException
Finally, I've also tried to create an error handling method (specifically for HttpNotFoundException, although I don't know how to separate HttpNotImplementedException) https://www.slimframework.com/docs/v4/middleware/error-handling.html, without any success.
Any help is highly appreciated.