覆盖 Symfony 2 异常



根据此文档页面:

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

Symfony使用TwigBundle来控制异常的显示。但是,正如文档中提到的,我不想自定义显示,我希望覆盖它。我正在开发一个小型的 REST API,我想覆盖对我的捆绑包的 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: FQCNOfYourExceptionListener
  tags:
    - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

Bellow是我的AppKernel的一部分.php用于禁用Symfony对JSON请求的内部异常捕获,(您可以覆盖handle方法而不是创建第二个方法)

use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpKernelHttpKernelInterface;
use SymfonyComponentHttpKernelKernel;
use SymfonyComponentConfigLoaderLoaderInterface;
class AppKernel extends Kernel {
  public function init() {
    parent::init();
    if ($this->debug) {
      // workaround for nasty PHP BUG when E_STRICT errors are reported
      error_reporting(E_ALL);
    }
  }
  public function handleForJson(Request $request,
                                $type = HttpKernelInterface::MASTER_REQUEST,
                                $catch = true
  ) {
    return parent::handle($request, $type, false);
  }
  ...

最新更新