php – 覆盖Symfony 2异常?

根据此文档页面

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

Symfony使用TwigBundle来控制异常的显示.但是,我不打算自定义显示,如文档中所述,我想覆盖它.我正在研究一个小的REST API,我想覆盖对我的bundle调用TwigBundle,进行自己的异常处理(就REST而言:映射正确的HTTP状态代码和纯文本正文响应).

我找不到任何关于这个的内容,手册上的参考文献并不是那么好,特别是在内核部分.也许有人已经这样做了,可以帮助我吗?谢谢.

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

在异常监听器类上

//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 }

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...