本文介绍了Symfony 2错误页面响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Angular编写的SPA和Symfony2 API一起使用.我希望错误响应(例如500)以json格式而不是HTML重新调整,而HTML根据文档此处是开箱即用的.

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.

我只是找不到任何地方向我展示如何明确指定我想要json格式.我以为拥有请求标头'Accept':'application/json'是它在谈论的内容,但是它不能如另一个问题

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

如何让throw new NotFoundHttpException('Could not find....');返回与默认HTML相对的json响应.

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

推荐答案

您可以通过两种方式设置格式:

You can set format in two ways:

    路径路径中的
  1. {_format}占位符

在您的控制器中调用$request->setRequestFormat('json')方法

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

这篇关于Symfony 2错误页面响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 04:39