In my application I'm using FastRoute and I would like to have different types of 404 responses:
- When a call is made to a not existing endpoint starting with
/api
then the application should return a JSON 404 response. - When a call is made to a not existing endpoint then the application should return a generic 404.
To get a generic 404 response I did as per the documentation:
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::NOT_FOUND:
// ... 404 Not Found
break;
But I'm having trouble finding a way to get a 404 JSON response in case of a not existing /api
endpoint.
What I achieved so this:
$router->addGroup('/api', function (RouteCollector $r) {
$r->post('/login', 'ApiController@login');
$r->addRoute('*', '[/{str}]', 'ApiController@notFound');
});
For example:
- when calling
/api/not-existing-endpoint
it returns a JSON 404 response (so it's OK). - when calling
/api/not-existing-endpoint/aaa/bbb/ccc
it does not catch it and it returns a generic 404.
How can fix the pattern of the route $r->addRoute('*', '[/{str}]', 'ApiController@notFound');
in order to also catch the nested URIs like /api/aaa/bbb/ccc/ddd
?
use route path with regular expression.
My full code.
Tested:
Alternative
I would recommend you to use 404 route to handle this instead. It is better and easier to manage your code in the future because it will not mixed with normal route.
My full code.