How to add 404 error code when the route does not exist?

How can I reset error code 404 when the route does not exist?

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

+5
source share
3 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 sentences that others posted regarding the .htaccess file, but above, as you do in Phalcon, without touching anything else.

, , , Phalcon ( ).

Nesbert gist

+6

​​ 404, , , URL- . .htaccess:

ErrorDocument 404 /404.php

404 . , errormessages

 ErrorDocument 404 /errormessages/404.php 
+5

If you want to use HTTP 404 Error by default when executing a PHP script:

header("HTTP/1.0 404 Not Found");

But remember that this is the first thing you send to the customer.

If you do not configure the default PHP error for the web server, this is software dependent. Easy to find filde apache uses this error for instances.

0
source

All Articles