cakephp 3 中的 JSON 异常

Tac*_*uls 5 json exception httpresponse cakephp-3.0

我正在 cakephp 中做一个 Restfull api...有时我会抛出一些异常。例如:

if (!$this->request->is('post')) {
            throw new MethodNotAllowedException("The requested resource does not support http method " . $this->request->param('_method'));
        }
Run Code Online (Sandbox Code Playgroud)

我的问题是,当 url 为 /controller/action.json 时,响应为:

{
message: "The requested resource does not support http method GET",
url: "/api/auth/users/authenticate.json",
code: 405
}
Run Code Online (Sandbox Code Playgroud)

采用 json 格式,但是,当我的 url 是 /controller/action 时。我的响应是 HTML,我想知道是否可以强制这些异常始终为 json,而不将 .json 放入 url 中。

谢谢!

fib*_*lan 4

您可以强制异常始终以 json 形式呈现,添加到Controller/ErrorController.php (in beforeRender)

$this->RequestHandler->renderAs($this, 'json');
Run Code Online (Sandbox Code Playgroud)