Home » Php » php – Overriding Symfony 2 exceptions?

php – Overriding Symfony 2 exceptions?

Posted by: admin July 12, 2020 Leave a comment


Accordingly to this doc page:


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.

How to&Answers:

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

  class: FQCN\Of\YourExceptionListener
    - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }


Bellow is part of my AppKernel.php for disabling internal Exception catch by Symfony for JSON requests, (you can override handle method instead of creating second one)

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() {

    if ($this->debug) {
      // workaround for nasty PHP BUG when E_STRICT errors are reported

  public function handleForJson(Request $request,
                                $type = HttpKernelInterface::MASTER_REQUEST,
                                $catch = true
  ) {
    return parent::handle($request, $type, false);