March 13, 2017

API environment contextual responses with Symfony3 Subscribers for Dev vs. Non-Dev

According to the ideal 12 Factor App you want to store your configuration in the specific environment. This includes debugging, logging, and everything else your application does. When building an API, these days you want your response data to be JSON, unless you’re an XML holdout which case you’re still using XML. Regardless, while in production you want clear and concise error message responses that do not reveal too much information. However, outside of production you probably want a quick way to see at least the source file throwing the exception so you know where to begin without crawling logs for every iterative issue while in development. For this you’ll need your…

June 16, 2015

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: An ApiExceptionListener class that processes the onKernelException event. 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…