如何在 Symfony4 中显示 404 错误页面而不是错误

You*_*aid 4 symfony symfony4

这是我的页面: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 %}
Run Code Online (Sandbox Code Playgroud)

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

# config/routes/dev/twig.yaml
_errors:
    resource: '@TwigBundle/Resources/config/routing/errors.xml'
    prefix:   /_error
Run Code Online (Sandbox Code Playgroud)

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

# config/packages/twig.yaml
twig:
    exception_controller: App\Controller\ExceptionController::showException
Run Code Online (Sandbox Code Playgroud)

我应该做什么才能让它发挥作用?

  • 顺便说一下,我使用了第一种方法覆盖默认的错误模板。

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

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

Ban*_*ple 6

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

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

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