Overriding Symfony 2 exceptions?
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 }
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); } ...