首页 > 解决方案 > 如何在 Symfony4 中显示 404 错误页面而不是错误

问题描述

这是我的页面:error404.html.twig 作为文档示例 404 错误模板

{# templates/bundles/TwigBundle/Exception/error404.html.twig #} 
{% extends 'base.html.twig' %}
{% block body %}
<h1>Page not found</h1>
        <p>
            The requested page couldn't be located. Checkout for any URL
            misspelling or <a href="{{ path('homepage') }}">return to the homepage</a>.
        </p>

{% endblock %}

这是我的页面 config/routes/dev/twig.yaml

# config/routes/dev/twig.yaml
_errors:
    resource: '@TwigBundle/Resources/config/routing/errors.xml'
    prefix:   /_error

这是我的页面 config/packages/twig.yaml

# config/packages/twig.yaml
twig:
    exception_controller: App\Controller\ExceptionController::showException

我应该怎么做才能使它起作用?

错误是: : 在此处输入图像描述

服务.yaml: 在此处输入图像描述

标签: symfonysymfony4

解决方案


如果您处于调试模式,而不是 404 页面,NotFoundHttpException那么一切都很好,因为这是记录和期望的行为,如下所述:https://symfony.com/doc/current/controller/error_pages。 html

在开发环境中,Symfony 捕获所有异常并显示一个特殊的异常页面

要绕过这个并实际查看您的自定义 404 页面,您需要通过特殊路径访问模板:http://localhost/index.php/_error/404


推荐阅读