JSON cakephp 3 异常

JSON exception in cakephp 3

我正在 cakephp 中休息 api... 有时我有一些抛出异常。例如:

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

我的问题是 url 是 /controller/action。json 响应是:

{
message: "The requested resource does not support http method GET",
url: "/api/auth/users/authenticate.json",
code: 405
}

在 json 格式中,但是,当我的 url 是 /controller/action 时。我的回答是 HTML,我想知道是否可以强制这些异常总是 json 而无需将 .json 放入 url.

谢谢!

在操作中执行以下操作。正如注释中所建议的那样。

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

为此,您还需要该组件。

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

您可以在 json 中添加 Controller/ErrorController.php(在 beforeRender 中)强制始终呈现异常

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