有没有一种方法可以通过Yii框架来发送/记录PHP致命错误的电子邮件?
例如,可以配置Yii发送“未定义变量”错误的电子邮件,但是致命错误只能由单独的、不与框架集成的代码监视,这并不理想。
有没有一种方法可以通过Yii框架来发送/记录PHP致命错误的电子邮件?
例如,可以配置Yii发送“未定义变量”错误的电子邮件,但是致命错误只能由单独的、不与框架集成的代码监视,这并不理想。
register_shutdown_function()
函数拦截致命错误。// Early fatal errors handler, it will be replaced by a full featured one in Controller class
// (given it does not have any parse or fatal errors of its own)
function earlyFatalErrorHandler($unregister = false)
{
// Functionality for "unregistering" shutdown function
static $unregistered;
if ($unregister) $unregistered = true;
if ($unregistered) return;
// 1. error_get_last() returns NULL if error handled via set_error_handler
// 2. error_get_last() returns error even if error_reporting level less then error
$error = error_get_last();
// Fatal errors
$errorsToHandle = E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING;
if ((!defined('APP_PRODUCTION_MODE') || APP_PRODUCTION_MODE) && !is_null($error) && ($error['type'] & $errorsToHandle))
{
$message = 'FATAL ERROR: ' . $error['message'];
if (!empty($error['file'])) $message .= ' (' . $error['file'] . ' :' . $error['line']. ')';
mail('errors@YOURDOMAIN.COM', $message, print_r($error, 1));
// Tell customer that you are aware of the issue and will take care of things
// echo "Apocalypse now!!!";
}
}
register_shutdown_function('earlyFatalErrorHandler');
/**
* Controller is the customized base controller class.
* All controller classes for this application should extend from this base class.
*/
class Controller extends CController
{
// ...
public function init()
{
register_shutdown_function(array($this, 'onShutdownHandler'));
earlyFatalErrorHandler(true); // Unregister early hanlder
}
public function onShutdownHandler()
{
// 1. error_get_last() returns NULL if error handled via set_error_handler
// 2. error_get_last() returns error even if error_reporting level less then error
$error = error_get_last();
// Fatal errors
$errorsToHandle = E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING;
if (!is_null($error) && ($error['type'] & $errorsToHandle))
{
// It's better to set errorAction = null to use system view "error.php" instead of
// run another controller/action (less possibility of additional errors)
Yii::app()->errorHandler->errorAction = null;
$message = 'FATAL ERROR: ' . $error['message'];
if (!empty($error['file'])) $message .= ' (' . $error['file'] . ' :' . $error['line']. ')';
// Force log & flush as logs were already processed as the error is fatal
Yii::log($message, CLogger::LEVEL_ERROR, 'php');
Yii::getLogger()->flush(true);
// Pass the error to Yii error handler (standard or a custom handler you may be using)
Yii::app()->handleError($error['type'], 'Fatal error: ' . $error['message'], $error['file'], $error['line']);
}
}
// ...
}