如何在路由不存在时添加404错误代码?

use*_*949 5 php routing http-status-code-404 phalcon

当路由不存在时,如何抛出404错误代码?

在您设置路由信息后的phalcon中 - 有没有办法检查来自(来自用户)的路由是否与路由列表中的任何路由匹配?然后,如果路由不存在,则抛出404错误.

Nik*_*los 6

你可以使用这样的东西:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用Micro组件,可以使用:

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

当然,你可以使用其他人发布的关于.htaccess文件的建议,但上面是你在Phalcon中如何做而不触及任何其他内容.

管道中还有一个新功能,涉及一个默认的错误处理程序,可以处理Phalcon中的错误(或必要时覆盖).

归功于Nesbert的要点


Nul*_*teя 5

完成404页面设置后,您只需将访问者发送到此页面的错误网址即可.要执行此操作,只需将以下行添加到.htaccess文件中:

ErrorDocument 404 /404.php
Run Code Online (Sandbox Code Playgroud)

您可以将404错误模板放在任何您想要的位置.例如,您可以将所有错误消息放在名为errormessages的文件夹中

 ErrorDocument 404 /errormessages/404.php 
Run Code Online (Sandbox Code Playgroud)