How do I extend FOSRestBundle’s normalizer to decorate output with data from exception?

Right now, when there is an HttpException thrown, it gets intercepted, and I get a response with JSON like:

{
  "code": 403,
  "message": "Forbidden"
}

I created a custom base class ExpandedHttpException:

class ExpandedHttpException extends HttpException {
    public readonly array $data;
}

Now, I’d like to make the response body like this if an exception that extends ExpandedHttpException is thrown:

{
  "code": 403,
  "message": "Forbidden",
  "data": {...}
}

As I discovered, the actual serialization happens within FOS\RestBundle\Serializer\Normalizer\FlattenExceptionNormalizer::normalize() but I can neither extend it (it’s final) nor replace (it makes use of FOSRest’s internal classes). So, how do I decorate the standard response with extra data?

Leave a Comment