Home » Php » php – Overriding Symfony 2 exceptions?

php – Overriding Symfony 2 exceptions?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Accordingly to this doc page:

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

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

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

Answer:

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() {
    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);
  }
  ...