Symfony2 : customize error pages for different bundles

岁酱吖の 提交于 2019-12-20 10:35:22

问题


I have several bundles and I'd like to know if it is possible to customize for each bundle their own error pages.

I read the cookbook and the examples show only a generic customize page for all bundles.

Is there a way to override the exception process for each bundle ?


回答1:


The listener itself would have to detect that - I'm not aware of any way to specify a listener for a single bundle.

<?

namespace Your\MainBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class YourExceptionListener
{
  public function onKernelException(GetResponseForExceptionEvent $event)
  {
    $exception = $event->getException();
    $namespace = new \ReflectionObject( $event->getController() )->getNamespaceName();

    switch ( $namespace )
    {
      case 'Acme\\DemoBundle':
        // do whatever with $exception here
        break;
      case 'Some\\OtherBundle':
        // do whatever with $exception here
        break;
      case 'Your\\MainBundle':
        // do whatever with $exception here
        break;
      default;
        // default
    }
  }
}

And register it

//services.yml
kernel.listener.yourlistener:
  class: Your\MainBundle\YourExceptionListener
  tags:
    - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }



回答2:


There's a bundle i've made for catch different errors pages from routes regex configuration, it works from the "kernel.exception_listener" listener and the "kernel.exception" event as described in documentation (http://symfony.com/doc/current/cookbook/controller/error_pages.html#use-kernel-exception-event).

With this bundle, you can:

  • Change the twig exception template from regex of the route you want
  • Change the twig exception template for certains http status code only
  • Enable / Disable the custom template for the debug mode

Link to the bundle (MIT licence): https://github.com/Kwrz/TwigException

Thanks for your idea Peter, I think add a feature in the next version of my bundle to define the template from the corresponding bundle namespace.



来源:https://stackoverflow.com/questions/11117508/symfony2-customize-error-pages-for-different-bundles

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!