0

我的目标是得到一个 JSON

{ 
  "meta": { 
    "error_type": "error type", 
    "code": 400, 
    "error_message": "error msg" 
  } 
}

万一出了什么问题。我试图将 try catch 块放在其余控制器的操作和模型中,但我得到了整个异常堆栈(我的意思是布局 + 视图)

什么是正确的方法?

4

2 回答 2

0

[我尝试将 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 数据,我得到了带有布局的整个默认异常堆栈。

于 2013-03-17T21:33:06.983 回答
0

在控制器操作中捕获异常。

从包含异常信息的操作中返回一个 JsonModel:

public function someAction()
{
    try {
        throw new Exception();
    }
    catch (Exception $e) {
        return new JsonModel(array(
            'meta' => array(
                'code'          => $e->getCode(),
                'error_message' => $e->getMessage(),
                //...
            )
        ));
    }
    //...
}

来源:从 ZF2 控制器操作返回 JSON

于 2013-03-17T19:03:33.100 回答