Divyesh Savaliya
Divyesh Savaliya

Reputation: 2740

slim framework Method notFound is not a valid method

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

Upvotes: 3

Views: 3442

Answers (1)

the-noob
the-noob

Reputation: 1342

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);

Upvotes: 3

Related Questions