2014-01-31 89 views
0

在zend 2中,無論何時發生異常,無論與該異常有關的控制器如何發生內部服務器錯誤?如何在zend 2中發生異常時發生內部服務器錯誤

對於內部服務器錯誤,我只是將狀態碼設置爲500!

+0

我把它用,無論你想設置全局,而不是需要修改每個控制器和行動解決方案,控制你的意思嗎? –

+0

是的,我的意思是全球! –

回答

1

在您的Module.php的onBootstrap()附加一個事件來監聽調度錯誤。

$eventManager = $e->getApplication()->getEventManager(); 
$eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function($event){ 
    $response = $event->getResponse(); 
    $response->setStatusCode(500); 
    return $response; 
}); 
0

如果你扔在MvcEvent :: EVENT_ROUTE或MvcEvent的聽衆錯誤:: EVENT_DISPATCH那麼你必須自己捕捉異常。

public function onDispatch(MvcEvent $event) 
{ 
    $routeMatch  = $event->getRouteMatch(); 
    $controllerName = $routeMatch->getParam('controller', 'not-found'); 
    /** @var Application $application */ 
    $application  = $event->getApplication(); 
    $events   = $application->getEventManager(); 
    $route   = $routeMatch->getMatchedRouteName(); 
    $request   = $event->getRequest(); 
    $controllerLoader = $application->getServiceManager()->get('ControllerManager'); 

    if ($controllerLoader->has($controllerName)) { 
     $controller = $controllerLoader->get($controllerName); 
     try { 
      if ($route == "requests" && $request instanceof Request && $request->getMethod() == 'POST') { 
       $this->checkAuthRequest($request); 
      } 
     } catch (\Exception $ex) { 
      $event->setError($application::ERROR_EXCEPTION) 
       ->setController($controllerName) 
       ->setControllerClass(get_class($controller)) 
       ->setParam('exception', $ex); 
      $events->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event); 
     } 
    } 
} 
相關問題