Symfony 2 error page response

試著忘記壹切 提交于 2019-12-24 05:08:07

问题


I have a SPA written in Angular used with a Symfony2 API. I want error responses like 500 to be retuned in json format rather than the HTML which according to the docs here is supported out the box.

For error pages, it first looks for a template for the given format and status code (like error404.json.twig);

I just cannot find anywhere that shows me how to explicitly specify that I want the json format. I thought having the request header 'Accept': 'application/json' was what it was talking about however that does not work as mentioned in another question here

How can I have throw new NotFoundHttpException('Could not find....'); return a json response opposed to the default HTML.


回答1:


You can set format in two ways:

  1. {_format} placeholder in route's path,

  2. In your controller call $request->setRequestFormat('json') method


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


来源:https://stackoverflow.com/questions/29682298/symfony-2-error-page-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!