2017-05-04 91 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');