2

在我的Zend Framework項目中,我使用了一個服務層,但是我並不知道在哪裏處理錯誤。如何在使用服務層時處理錯誤?

例如,假設我有一個UserService::updateUser($data);

如果我有:

$data = array(
    'userId' => 2, 
    'firstName' => 'Jane', 
    'lastName' => 'Doe', 
); 

而且用戶ID爲2不存在?

你會在哪裏以及如何處理這樣的錯誤?

回答

1

您可以轉發到特定的控制器處理所有業務的錯誤,像這樣:

if ($error=true) 
     return $this->_forward('standarderror', 'businesserror', 'default', 
       array('msgtitle' => $this->view->translate('item_not_found'), 
        'msg' => $this->view->translate('item_not_found_msg'))); 

,並在您BusinesserrorController樣子:

class BusinesserrorController extends Zend_Controller_Action { 

public function init() { 
    $this->_helper->viewRenderer->setNoRender(); 
} 

public function standarderrorAction() { 
    $msgtitle = $this->_getParam('msgtitle'); 
    $msg = $this->_getParam('msg'); 

    $this->view->errortitle = $msgtitle; 
    $this->view->errormessage = $msg; 

    $this->view->nextstep = $this->view->translate('return_to_the_homepage'); 
    $this->view->nextstepurl = "/"; 

    echo $this->render('error/businesserror', null, true); 
} 

} 

可以參數化的轉發URL以及;)