7

根据此文档页面:

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

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

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

4

2 回答 2

13

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

On exception listener class

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

The service declaration would be

 //services.yml
 kernel.listener.yourlisener:
  class: FQCN\Of\YourExceptionListener
  tags:
    - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
于 2012-04-26T15:52:19.793 回答
1

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

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

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);
  }
  ...
于 2012-04-26T15:40:59.683 回答