问题描述
我正在用cakephp做一个restfull api ...有时我会抛出一些异常.例如:
I'm doing a restfull api in cakephp...And sometime i have some throw exceptions. For example:
if (!$this->request->is('post')) {
throw new MethodNotAllowedException("The requested resource does not support http method " . $this->request->param('_method'));
}
我的问题是,当url为/controller/action.json时,响应为:
My problem is when the url is /controller/action.json the response is :
{
message: "The requested resource does not support http method GET",
url: "/api/auth/users/authenticate.json",
code: 405
}
采用json格式,但是当我的网址是/controller/action时.我的回应是HTML,我想知道是否有可能在不将.json放入url的情况下强制将这些异常始终设置为json.
In json format, but, when my url is /controller/action. My response is HTML, i want to know if is possible to force these exceptions to be always json without putting .json in the url.
谢谢!
推荐答案
您可以强制将异常始终在json中呈现,并添加到 Controller/ErrorController.php (在beforeRender
中)
You can force exceptions to be always rendered in json adding in Controller/ErrorController.php (in beforeRender
)
$this->RequestHandler->renderAs($this, 'json');
这篇关于Cakephp 3中的JSON异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!