私の目標は、次のような JSON を取得することです
{
"meta": {
"error_type": "error type",
"code": 400,
"error_message": "error msg"
}
}
何か問題が発生した場合。残りのコントローラーのアクションとモデルの両方にtry catchブロックを配置しようとしましたが、例外スタック全体を取得します(レイアウト+ビューを意味します)
正しい方法は何ですか?
私の目標は、次のような JSON を取得することです
{
"meta": {
"error_type": "error type",
"code": 400,
"error_message": "error msg"
}
}
何か問題が発生した場合。残りのコントローラーのアクションとモデルの両方にtry catchブロックを配置しようとしましたが、例外スタック全体を取得します(レイアウト+ビューを意味します)
正しい方法は何ですか?
コントローラー アクションで例外をキャッチします。
例外情報を含むアクションから JsonModel を返します。
public function someAction()
{
try {
throw new Exception();
}
catch (Exception $e) {
return new JsonModel(array(
'meta' => array(
'code' => $e->getCode(),
'error_message' => $e->getMessage(),
//...
)
));
}
//...
}
【アクションレストコントローラーにtry catchブロックを両方入れてみた】
私はちょうどのように試しました(私は私の目標を実現したいのですが、何かがうまくいかない場合のみ:))
public function create($data)
{
try{
$artist = $this->getRequest()->getPost('artist', null);
$title = $this->getRequest()->getPost('title', null);
$album = new Album();
$album->exchangeArray(array('artist'=>$artist,'title'=>$title));
$id = $this->getAlbumTable()->saveAlbum($album);
return $this->get($id);
}
catch (Exception $e) {
return new JsonModel(array(
'meta' =>array(
'code'=>500,
'error-num'=>$e->getCode(),
'error-msg'=>$e->getMessage(),
)
));
}
}
しかし、上記のようにjsonデータの代わりに機能しません。レイアウト付きのデフォルトの例外スタック全体を取得します。