I'm using FOSRestBundle with Symfony 2 to implement a REST API in JSON format.
I want all API exceptions to be returned in a specific JSON format like this:
{
"success": false,
"exception": {
"exceptionClass": "SomeNastyException",
"message": "A nasty exception occurred"
}
}
How do I do this?
I've tried to fiddle with ExceptionController, but it's logic seems too complicated to be easily overloaded.
Note: This works only for FOSResBundle < 2.0. For FOSResBundle >= 2.0 please use Exception Normalizers, see examples.
You can write custom exception wrapper handler like in docs. In your case:
app/config/config.yml
Response example:
I've landed on this thread a number of times over the last few days. For anyone else in my situation where you are using V2 of the bundle, you may find the following resource on upgrading FOSRestBundle useful.
It covers the use of serializer in place of ExceptionWrapperHandlerInterface.
https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/UPGRADING-2.0.md
Before:
config.yml
Handler
After (if you use the Symfony serializer):
services.yml
normalizer