2

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 ?

4
  • You can simply return a new Response(json_encode(...)) with the appropriate headers of course. Commented Oct 28, 2016 at 10:03
  • It's indeed what I did for the moment. But I'd really like to be able to make the difference in the code between a simple page returning a Json code and an exception returning a Json code... Commented Oct 28, 2016 at 12:02
  • You could handle that via an exception handler, a standard json response, an exception bubbling class(fancy word for exception handler class) and I'm sure there are other ways. Commented Oct 28, 2016 at 12:05
  • Return new JSONResponse if you don't whant to se the appropriate headers Commented Oct 28, 2016 at 13:38

1 Answer 1

2

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.