Show a specific route instead of error page (404) - Symfony2

前端 未结 3 1515
面向向阳花
面向向阳花 2020-12-15 10:08

Instead of an error page / 404 I want to just show the /sitemap page. Of course I don\'t want a redirect and I still want the 404 HTTP response header to be set.

Is

3条回答
  •  一生所求
    2020-12-15 10:46

    As shown in the Symfony Cookbook you can override error pages in two ways:

    • Overriding the templates
    • Using a custom exception controller

    If you only want to show the /sitemap route on a 404 (HttpNotFoundException) exception you could override the Twig exception template by creating a new template in app/Resources/TwigBundle/views/Exception/error404.html.twig.

    Another way that is not shown in the cookbook is using an event listener. When the kernel encounters an exception, a kernel.exception event is dispatched. By default, this exception is caught by the exception listening provided by Twig. You can create your own event listener which listens for the kernel.exception event and renders a page:

    getException() instanceof NotFoundHttpException) {
            $response = $this->templating->renderResponse(/* sitemap */);
    
            $event->setResponse($response)
        }
    }
    

    (I haven't tested this code, so you should try it yourself! And you have to inject the templating service into the event listener yourself, of course).

提交回复
热议问题