I'd like to create a custom Exception on Symfony3 that returns a JSON response to be able to handle it in JavaScript afterwards.
Does someone know if it's possible and how to do it ?
Create a new exception handler class, like this:
namespace AppBundle\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class ExceptionSubscriber implements EventSubscriberInterface
{
/* ... */
public static function getSubscribedEvents()
{
return [ KernelEvents::EXCEPTION => 'onKernelException' ];
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$customResponse = new JsonResponse(['error' => 'My custom error message']);
$event->setResponse($customResponse);
}
}
Don't forget to register the new service in app/config/services.yml:
app.exception_subscriber:
class: AppBundle\Subscriber\ExceptionSubscriber
tags:
- { name: kernel.event_subscriber }
new Response(json_encode(...))with the appropriate headers of course.