Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
714 views
in Technique[技术] by (71.8m points)

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

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 this possible? All I can see is how to set templates in Twig.

I definitely don't want a redirect.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

<?php
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
use SymfonyComponentHttpKernelEventGetResponseForExceptionEvent;
use SymfonyComponentHttpFoundationResponse;

public function onKernelException(GetResponseForExceptionEvent $event)
{
    if ($event->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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...