JSON exception in cakephp 3

时光总嘲笑我的痴心妄想 提交于 2021-02-07 08:01:38

问题


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'));
        }

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
}

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.

Thanks!


回答1:


You can force exceptions to be always rendered in json adding in Controller/ErrorController.php (in beforeRender)

$this->RequestHandler->renderAs($this, 'json');



回答2:


In the action do the following. As suggested in the notes.

if (!$this->request->is('post')) {
    $this->RequestHandler->renderAs($this, 'json');
    throw new MethodNotAllowedException("The requested resource does not support http method " . $this->request->param('_method'));
}

For this to work you will need the component too.

public function initialize() {
    parent::initialize();
    $this->loadComponent('RequestHandler');
}


来源:https://stackoverflow.com/questions/43790672/json-exception-in-cakephp-3

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