We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to return 404 when using default routes

Hi,

I have a route.php file that contains the following defintions towards the bottom:

$router->notFound( [ "controller" => "Index", "action" => "index" ]);

return $router;

which essentially call the IndexController::indexAction when the provided path is not matched by any other route. This specific action returns status 200 OK and some dummy json content.

public function indexAction() {
    $response = new Response();
    $response->setStatusCode(200);
    $response->setJsonContent( ["data" => "Invalid route."] );
    $response->setContentType("application/json");
    return $response;
}

However, sometimes one of my other routes needs to return status 404 Not found. What I have in those action methods is something like this:

$response = new Response();
$response->setStatusCode(404);
return $response;

The side effect of this is that the routing table continues to be processed and ends up in the default route, so my dummy json then gets displayed, albeit with the correct 404 Not Found status.

Can someone tell me how to completly control the output from the initial controller where the 404 Not Found is initially set?

edited Mar '16

And why are you not using

public function indexAction() {
    $response = new Response();
    $response->setStatusCode(404);
    $response->setJsonContent( ["data" => "Invalid route."] );
    $response->setContentType("application/json");
    return $response;
}

if route does not exists? Why are you returning status 200? Does not make sence for me. In REST APIs, you should return status 404 on nonexisting routes not status 200.