Throw Exception based on Accept Header

Symfony has a wonderful onKernelException event that we can expose in an Event Listener to properly handle exceptions in our applications.

In one particular use case, we want to handle JSON and XML responses for our exceptions that are thrown via our API. In this case, we need to format and render our exception based on the Accept Header of the initial request.

This is handled in two simple steps:

  1. An ApiExceptionListener class that processes the onKernelException event.
  2. A service declaration that tells the Symfony kernel about our Event Listener.

The Exception Listener

We need to be careful above not to check the Accept header for XML because some browsers will give a false positive on this. As such, we check instead for an AJAX request that was not JSON, which thus must be XML.

Defining the service

Sample Response

Now that we’ve got this setup, our exception messages are nice and clean:

 

Leave a Reply

Your email address will not be published. Required fields are marked *