I am creating an api using the Slim framework for the first time.
I want to return a specific response if url not found.
I use notFound function of Slim framework as follows:
$app->notFound(function () use ($app) {
$res = array("msg"=>"page not found");
$response->getBody()->write(json_encode($res));
return $response;
});
but when I add this line of code in my php page it shows me following error:
Fatal error: Uncaught exception 'BadMethodCallException' with message 'Method notFound is not a valid method' in C:\wamp\www\api\vendor\slim\slim\Slim\App.php on line 129
BadMethodCallException: Method notFound is not a valid method in C:\wamp\www\api\vendor\slim\slim\Slim\App.php on line 129
Seems you are using Slim 3 with some code from Slim 2.
In 3 you can do it by adding a handler in the container (mode details here) or by adding a middleware:
Edit - as @geggleto points out, I forgot to mention that for the code below you should also set $settings['determineRouteBeforeAppMiddleware'] = true
/**
* check if route exists
*/
$middleware = function (Request $request, Response $response, $next) {
if (!$request->getAttribute('route')) {
$res = array("msg"=>"page not found");
$response->getBody()->write(json_encode($res));
return $response;
}
return $next($request, $response);
};
$app->add($middleware);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With