2017-05-04 33 views
0

我在cakephp做了一个restfull api ... 有时我有一些抛出异常。例如:cakephp 3中的JSON异常

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

我的问题是当网址/controller/action.json的回应是:

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

JSON格式,但是,当我的网址/控制器/动作。我的回复是HTML,我想知道是否有可能强制这些例外总是json没有将.json放在url中。

谢谢!

+0

您可以指定在响应头'应用/ json'。 – TheDude

+0

你可以使用'$ this-> RequestHandler-> renderAs($ this,'json');' –

+0

我在控制器中添加了我的动作,然后抛出异常...但没有成功......异常呈现作为HTML ... – jaloise

回答

0

在该操作中执行以下操作。正如笔记所建议的那样。

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

是的,我这样做在我的控制器...但仍然呈现为HTML ..我不知道为什么... – jaloise

+0

@jaloise我回家时尝试更多的东西,因为我相信我以前有过这个工作。你也可以自己直接编写响应对象'$ this-> response'而不是抛出错误并让Cake处理它。 – KaffineAddict

+0

我尝试没有成功。 – jaloise

0

您可以强制例外总是被渲染JSON添加在控制器/ ErrorController.php(在beforeRender

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