Zend框架2推荐了错误处理方法

Teo*_*lov 15 php error-handling zend-framework zend-framework2

我注意到Zend提供的Skeleton Application无法处理error 500.我知道在ZF1中有一个ErrorController可以解决这个问题.我在网上做了一些研究,但没有找到明确的解决方案.

那么ZF2中错误处理的最佳方法是什么?它是基于每个模块还是一些全局异常/错误处理程序?

我知道另一个解决方案是添加ini_set('display_errors', true);到我的index.php,但我真的不喜欢这个解决方案.似乎框架应该提供一些处理错误的方法.

Moh*_*din 31

您可以在捕获之后以任何方式处理异常,例如以下示例,其中您将全局捕获异常...:

在你的onBootstrap方法中Module.php你可以附加一个在事件发生时执行的函数,下面附加一个在引发错误(异常)时要执行的函数:

public function onBootstrap(MvcEvent $e)
{
    $application = $e->getApplication();
    $em = $application->getEventManager();
    //handle the dispatch error (exception) 
    $em->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'handleError'));
    //handle the view render error (exception) 
    $em->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER_ERROR, array($this, 'handleError'));
}
Run Code Online (Sandbox Code Playgroud)

然后定义函数以任何方式处理错误,以下是一个示例:

public function handleError(MvcEvent $e)
{
    //get the exception
    $exception = $e->getParam('exception');
    //...handle the exception... maybe log it and redirect to another page, 
    //or send an email that an exception occurred...
}
Run Code Online (Sandbox Code Playgroud)