Igor Simic
5 years ago

Symfony - catch exceptions and send json response


How to catch Symfony framework exceptions and turn them into custom, nice json response? To achieve this we will use custom service and catch every exception and we will use JsonResponse to set the http error code and send it to frontend.


First let's create a class ExceptionListener and put it in folder src/EventListener
<?php
namespace App\EventListener;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;


class ExceptionListener
{
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        // You get the exception object from the received event
        $exception = $event->getException();
        
        // create json response and set the nice message from exception
        $customResponse = new JsonResponse(['status'=>false, 'message' => $exception->getMessage()],403);
        
        // set it as response and it will be sent
        $event->setResponse($customResponse);

    }
}

Next we need to register this class as a service, in services.yaml. Under services section paste this code:
services:
   ...
    App\EventListener\ExceptionListener:
        tags:
        - { name: kernel.event_listener, event: kernel.exception }

And voila! 
Cut and dry... that is it... simple as that!