Cakephp 3中的JSON异常 [英] JSON exception in cakephp 3

查看:62
本文介绍了Cakephp 3中的JSON异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用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异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆