覆盖Symfony 2异常? [英] Overriding Symfony 2 exceptions?

查看:19
本文介绍了覆盖Symfony 2异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此文档页面:

http://symfony.com/doc/current/cookbook/controller/error_pages.html

Symfony 使用 TwigBundle 来控制异常的显示.但是,正如文档中提到的那样,我不希望自定义显示,我希望覆盖它.我正在开发一个小型 REST API,我想将 TwigBundle 的调用覆盖到我的包中,进行我自己的异常处理(在 REST 方面:映射正确的 HTTP 状态代码和纯文本正文响应).

Symfony uses the TwigBundle to control the display of exceptions. However, i'm not looking to customize the display, as mentioned in the doc, i'm looking to override this. I'm working on a small REST API and i wanted to override the calling of TwigBundle to my bundle, making my own exceptions handling (in terms of REST: map correct HTTP status codes and plain-text body responses).

我找不到任何关于此的信息,手册上的参考也不是很好,特别是在内核部分.也许有人已经这样做了并且可以帮助我?谢谢.

I couldn't find anything about this and the reference on the manual is not that good, specially on the kernel part. Maybe someone already did this and can help me out? Thanks.

推荐答案

你应该创建一个监听 kernel.exception 事件的监听器.在该侦听器的 onKernelException 方法中,您可以检查您的异常,例如

You should create a listener that listens on kernel.exception event. In onKernelException method of that listener you can check for your exception e.g

关于异常监听器类

  //namespace declarations
  class YourExceptionListener
  {

      public function onKernelException(GetResponseForExceptionEvent $event)
      {
        $exception =  $event->getException();
        if ($exception instanceof YourException) {
            //create response, set status code etc.
            $event->setResponse($response); //event will stop propagating here. Will not call other listeners.
        }
      }
  }

服务声明为

 //services.yml
 kernel.listener.yourlisener:
  class: FQCN\Of\YourExceptionListener
  tags:
    - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

这篇关于覆盖Symfony 2异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆