gpt4 book ai didi

error-handling - 如何记录 ZF2 Controller 异常

转载 作者:行者123 更新时间:2023-12-04 06:42:07 24 4
gpt4 key购买 nike

我正在为异常注册一个 Zend\Log 实例,我需要最后通过电子邮件发送所有系统错误,现在它只是转到一个文件。但是,它在 Controller 中不起作用,异常显示在 View 中(或不显示,取决于 display_exceptions )。我找到了这个 bug ,似乎没有人太在意。所以我需要一个解决方法。有没有办法让 Controller 不吃我的异常?

'service_manager' => array(
'factories' => array(
'Logger' => function ($sm) use ($sRootDir)
{
$log = new Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream($sRootDir . '/temp/license.log');
$log->addWriter($writer);
Zend\Log\Logger::registerErrorHandler($log);
Zend\Log\Logger::registerExceptionHandler($log);
return $log;
},
),

最佳答案

您可以附加到调度错误事件:

Module.php

public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
/**
* Log any Uncaught Errors
*/
$sharedManager = $e->getApplication()->getEventManager()->getSharedManager();
$sm = $e->getApplication()->getServiceManager();
$sharedManager->attach('Zend\Mvc\Application', 'dispatch.error',
function($e) use ($sm) {
if ($e->getParam('exception')){
$sm->get('Logger')->crit($e->getParam('exception'));
}
}
);
}

一个简单记录器的示例服务配置
'factories' => array(
'Logger' => function($sm){
$logger = new \Zend\Log\Logger;
$writer = new \Zend\Log\Writer\Stream('./data/log/'.date('Y-m-d').'-error.log');
$logger->addWriter($writer);
return $logger;
},
// ...
);

您还可以记录堆栈中的所有异常,以便更好地了解到底出了什么问题,而不是只显示最后一个异常,因为它可能不包含太多信息。
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
/**
* Log any Uncaught Exceptions, including all Exceptions in the stack
*/
$sharedManager = $e->getApplication()->getEventManager()->getSharedManager();
$sm = $e->getApplication()->getServiceManager();
$sharedManager->attach('Zend\Mvc\Application', 'dispatch.error',
function($e) use ($sm) {
if ($e->getParam('exception')){
$ex = $e->getParam('exception');
do {
$sm->get('Logger')->crit(
sprintf(
"%s:%d %s (%d) [%s]\n",
$ex->getFile(),
$ex->getLine(),
$ex->getMessage(),
$ex->getCode(),
get_class($ex)
)
);
}
while($ex = $ex->getPrevious());
}
}
);
}

关于error-handling - 如何记录 ZF2 Controller 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15271250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com