【问题标题】:JSON exception in cakephp 3cakephp 3 中的 JSON 异常
【发布时间】:2017-10-03 02:13:55
【问题描述】:

我正在 cakephp 中做一个 restfull 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。

谢谢!

【问题讨论】:

  • 您可以在响应头中指定application/json
  • 你可以使用$this->RequestHandler->renderAs($this, 'json');
  • 在抛出异常之前,我将它添加到控制器中的操作中......但没有成功......异常呈现为 HTML......

标签: json exception cakephp-3.0 httpresponse


【解决方案1】:

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

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

【讨论】:

  • 这解决了我的问题。
  • 但是将它放入 Controller/ErrorController.php 不会影响所有错误,包括那些不需要 JSON 响应的错误?
【解决方案2】:

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

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

【讨论】:

  • 是的,我在我的控制器中这样做...但仍然呈现为 HTML ..我不知道为什么...
  • @jaloise 我回家后会尝试更多的东西,因为我相信我以前也有过这样的工作。您也可以自己直接编写响应对象$this->response,而不是抛出错误并让 Cake 处理它。
  • 我尝试过,但没有成功。
猜你喜欢
  • 1970-01-01
  • 2015-12-10
  • 2018-10-18
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
相关资源
最近更新 更多