问题
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:
{_format}
placeholder in route's path,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