Symfony 2 Page Error Message

I have a SPA written in Angular that is used with the Symfony2 API. I want error answers such as 500 to be reconfigured in json format, and not in HTML, which according to the docs is supported in the field here.

For error pages, first looks for a template for this format and status code (for example, error404.json.twig);

I just can't find anywhere that shows me how to explicitly indicate that I need json format. I thought the Accept request header: "application / json" was what he was talking about, however this does not work as mentioned in another question here

How can I throw new NotFoundHttpException('Could not find....');return a json response opposite HTML by default.

+2
source share
1 answer

You can set the format in two ways:

  • {_format} placeholder in the route of the route,

  • In the controller, a method call $request->setRequestFormat('json')


routeName:
    path: /news/{id}/show.{_format}
    defaults:
        _controller: BundleName:Controller:method
        format: json
    requirements:
        _format: json|xml|html # you can remove xml & html, if you no have there formats
+4
source

Source: https://habr.com/ru/post/1626101/


All Articles