Buy

Request Format: Why Exceptions Return HTML

When you throw an exception in Symfony - even an HttpException - it returns an HTML page. Notice the Content-Type header here of text/html. And in reality, this is returning a full, giant HTML exception page - my test helpers are just summarizing things.

Why is that? Why does Symfony default to the idea that if something goes wrong, it should return HTML?

Request Format

Here's the answer: for every single request, Symfony has what's called a "request format", and it defaults to html. But there are a number of different ways to say "Hey Symfony, the user wants json, so if something goes wrong, give them that".

The easiest way to set the request format is in your routing. Open up app/config/routing.yml:

8 lines app/config/routing.yml
... lines 1 - 4
app_api:
resource: "@AppBundle/Controller/Api"
type: annotation

When we import the routes from our API controllers, we want all of them to have a json request format. To do that, add a defaults key. Below that, set a magic key called _format to json:

10 lines app/config/routing.yml
... lines 1 - 4
app_api:
resource: "@AppBundle/Controller/Api"
type: annotation
defaults:
_format: json

For us, this is optional, because in a minute, we're going to completely take control of exceptions for our API. But with just this, re-run the tests:

./bin/phpunit -c app --filter testInvalidJson

Yes! Now we get a Content-Type header of application/json and because we're in the dev environment, it returns the full stack trace as JSON.

This is cool. But the JSON structure still won't be right. So let's take full control using our ApiProblemException.

Leave a comment!

  • 2016-10-10 Johan

    Maybe in Symfony 4, haha ;)

    I love your elaborate answers, thanks!

  • 2016-10-10 weaverryan

    Hey Johan!

    Unfortunately, there's nothing built in for that, but I like your thinking :). Of course, we have the HttpException class (really, the HttpExceptionInterface) and its sub-classes, but the default ExceptionListener in Symfony (which handles the response during an exception... by default), only uses this interface to get the status code and any headers you might want set. It still *always* renders this internal controller that always returns HTML. Well, as we learned here, it can also return JSON, but it's this more-or-less hardcoded, generic JSON page - you don't have a lot of control.

    So, good thinking... but it doesn't work that way :).

    Cheers!

  • 2016-10-08 Johan

    Just thinking ahead, but I hope I can just override a method in ApiProblemException that returns a customized Response :)