2013-03-17 50 views
0

我的目标是获得一个JSON像Zend框架2 AbstractRestfulController - 例外的JSON

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

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

什么是正确的方法?

回答

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(), 
       //... 
      ) 
     )); 
    } 
    //... 
} 

来源:Returning JSON from a ZF2 controller action

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数据我与布局 全默认异常堆栈。

+0

您可以将异常跟踪粘贴到要点中吗?这看起来不正常,在我看来,这个异常是在try-catch块之外引发的。 – Ocramius 2013-03-18 02:59:13

+0

触发异常我将艺术家专辑字段设置为唯一于$ curl -i -H“Accept:application/json”-X POST -d“artist = AC DC2&title = Dirty Deeds2”http:// localhost/zf2/public /休息两次,你可以看看整个堆栈http://pastebin.com/uLftaG7s – Whisher 2013-03-18 14:20:28

+0

我可以看到我可以看到..../Driver/Pdo/Statement.php:245 ...... – Whisher 2013-03-18 14:38:30