Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a 404 error code when route does not exisit?

How can I throw a 404 error code when a route does not exist?

In phalcon after you set up your routing information - is there a way to check to see if a route coming in (from the user) matches any of the routes in your routes list? Then, if the route does not exist, throw a 404 error.

like image 346
user1697949 Avatar asked Sep 25 '12 16:09

user1697949


1 Answers

You can use something like this:

public function main()
{
    try {

        $this->_registerServices();
        $this->registerModules(self::$modules);
        $this->handle()->send();

    } catch (Exception $e) {

        // TODO log exception

        // remove view contents from buffer
        ob_clean();

        $errorCode = 500;
        $errorView = 'errors/500_error.phtml';

        switch (true) {
            // 401 UNAUTHORIZED
            case $e->getCode() == 401:
                $errorCode = 401;
                $errorView = 'errors/401_unathorized.phtml';
                break;

            // 403 FORBIDDEN
            case $e->getCode() == 403:
                $errorCode = 403;
                $errorView = 'errors/403_forbidden.phtml';
                break;

            // 404 NOT FOUND
            case $e->getCode() == 404:
            case ($e instanceof Phalcon\Mvc\View\Exception):
            case ($e instanceof Phalcon\Mvc\Dispatcher\Exception):
                $errorCode = 404;
                $errorView = 'errors/404_not_found.phtml';
                break;
        }

        // Get error view contents. Since we are including the view
        // file here you can use PHP and local vars inside the error view.
        ob_start();
        include_once $errorView;
        $contents = ob_get_contents();
        ob_end_clean();

        // send view to header
        $response = $this->getDI()->getShared('response');
        $response->resetHeaders()
            ->setStatusCode($errorCode, null)
            ->setContent($contents)
            ->send();
    }
}

If you are using the Micro component you can use this:

$app->notFound(
    function () use ($app) {
        $app->response->setStatusCode(404, "Not Found")->sendHeaders();
        echo 'This is crazy, but this page was not found!';
    }
);

Of course you can use the suggestions that others posted regarding the .htaccess file, but above is how you do it in Phalcon without touching anything else.

There is also a new feature coming down the pipeline, regarding a default error handler that would process errors in Phalcon (or overriden if necessary).

Credits to Nesbert for the gist

like image 129
Nikolaos Dimopoulos Avatar answered Sep 23 '22 00:09

Nikolaos Dimopoulos