FriendsOfSymfony / FOSRestBundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony
http://symfony.com/doc/master/bundles/FOSRestBundle/index.html
MIT License
2.79k stars 707 forks source link

Clarifying proper Exception Controller Usage #2347

Open evang522 opened 2 years ago

evang522 commented 2 years ago

Hi all,

I am having a lot of trouble upgrading from 2.8.3 to 3.1 with regard to the custom exception codes and showing error messages.

After I upgraded, our endpoint error responses don't reflect the fos_rest.yml exception configuration. When they should return, for example, a 409 error because we threw a domain exception which should be mapped to 409, they instead return

{
    "code": 500,
    "message": "Internal Server Error"
}

this happens despite the fact that the actual HTTP status code of the response is 409. So the ResponseCodeStatus listener is clearly working, the serialization however is not. To my knowledge, after digging through logs and stack traces, there are no issues happening causing the serializer to fail.

I see that in the upgrade to major version 3, the FOS\RestBundle\Controller\TwigExceptionController was removed -- and when I look at the code for it, I see it was clearly equipped to do this custom exception mapping and render the JSON that I expect. Now the exception controller being used by the Symfony ExceptionListener is the Symfony\Bundle\TwigBundle\Controller\ExceptionController.

This Twigbundle exception controller doesn't seem to be equipped to serialize the JSON error as it doesn't contain any code relevant for reading the exception code mapping from FOSRestBundle and injecting this into the template it uses.

We also use JMS serializer with FOS/rest. If this TwigBundle ExceptionController is not the right controller, which one should we be using in order to properly serialize JSON errors in REST endpoints?

Below is some information about our versioning:

symfony/*: 4.4
"friendsofsymfony/rest-bundle": "^3.1.0"
"jms/serializer-bundle": "^3.10.0",
"symfony/twig-bundle": "^4.4.13",

fos_rest.yaml configuration:


exception:
  flatten_exception_format: legacy
  enabled: true
  serializer_error_renderer: true
  map_exception_codes: true
  codes:
          ... several mapped exceptions.

can anybody clarify for me what the proper configuration here is or if I'm missing something?

evang522 commented 2 years ago

Update: setting the error_controller in twig.yaml to null fixed this for me. It now appears to be using the newer Symfony ErrorListener and Error Controller, which properly serialize the data. Would be great to hear confirmation that this is the correct way to fix the problem.