Symfony2 Custom Error Exception Listener - Rendering templates or passing to a controller

前端 未结 2 1918
予麋鹿
予麋鹿 2021-01-06 16:23

I\'m trying to work out the best way of handling custom error pages within Symfony2.This includes 500 and 404\'s etc.

I can create my own custom templates (error404

相关标签:
2条回答
  • 2021-01-06 16:32

    The way I did to solve similar issue is: I dont know if it can help you out.

    const GENERIC_CODE = 550;
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        if ($exception instanceof RedirectableException) {
            $request = $event->getRequest();
            $url = $exception->getUrl($this->_authentication['base']['url']);
            $response = new Response();
            $response->setStatusCode(self::GENERIC_CODE, AuthenticationException::GENERIC_MESSAGE);
            $response->setContent($url);
            $event->setResponse($response);
       }
    }
    
    0 讨论(0)
  • 2021-01-06 16:55

    You should add into yours Listener

    /**
     *
     * @var ContainerInterface
     */
    private $container;
    
    function __construct($container) {
        $this->container = $container;
    }
    

    How do you register your Listener? You should register Listener like Service

    Like that

    core.exceptlistener:
      class: %core.exceptlistener.class%
      arguments: [@service_container]
      tags:
            - { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 200 }
    

    The best way is don't use service_container. The best way is register only necessary services.

    Like that

    /**
     *
     * @var Twig_Environment
     */
    private $twig;
    
    function __construct($twig) {
        $this->twig = $twig;
    }
    
    0 讨论(0)
提交回复
热议问题