如何在zend框架中记录数据库错误

时间:2013-05-13 12:12:38

标签: php zend-framework error-handling zend-db

我正在为我的项目使用zend framework 1.12。我想捕获所有类型的致命错误,并将它们发送到电子邮件地址以便快速修复。为此,我在Bootstrap.php文件中编写了下面提到的代码。

protected function _initFatalErrorCatcher()
{
    register_shutdown_function(array($this, 'errorlogHandler'));
}

public function errorlogHandler()
{
    $e = error_get_last();

if (!is_null($e)) { //fatal error

    $msg  = 'Fatal error: ' . $e['message'];
    $msg .= ' in' . $e['file'];
    $msg .= ' on line: ' . $e['line'];

    $mail = new Zend_Mail('utf-8');
    $mail->setBodyHtml($msg);
    $mail->setFrom('zzz@z.com');
    $mail->addTo('yyy@y.com');
    $mail->setSubject('check this error');

    $mail->send();
    }
}

使用上面的代码,我能够将除数据库连接相关错误和查询相关错误之外的致命错误发送到电子邮件。我也按照Catch Zend PDO Exception的说明进行操作,但我相信我错过了一些不起作用的东西。

对此有任何帮助将不胜感激。

修改

我也在使用Zend_Log在日志文件中写入错误日志。但是,使用这个我找不到写出致命错误的方法。代码如下。

$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH  . "/../data/log-file.log");
$errors = $this->_getParam('error_handler');
$exception = $errors->exception;

$log = new Zend_Log($writer);
$log->debug($exception->getMessage() . "\n" . $exception->getTraceAsString());

与数据库连接相关的问题的方案:

如果主机名,数据库名或用户名中有任何错误,它会在浏览器中显示致命错误,如下所示。但是它没有被register_shutdown_function()或Zend_Log()检测到。

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000] [1044] Access denied for user 'AAAA'@'%' to database 'BBBB'' in /var/www/project_name/library/Zend/Db/Adapter/Pdo/Abstract.php on line 144 PDOException: SQLSTATE[42000] [1044] Access denied for user 'AAAA'@'%' to database 'BBBB' in /var/www/project_name/library/Zend/Db/Adapter/Pdo/Abstract.php on line 129

3 个答案:

答案 0 :(得分:1)

帖子here显示了一个示例。基本上使用set_error_handler来阻止php在遇到错误时抛出异常。这个例子来自链接:

<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>  

希望这有帮助

答案 1 :(得分:0)

// $ array包含insert

的值
try {
    $this->db->insert('Users', $array );
} catch (Exception $e){
    echo $e->getMessage();
}

答案 2 :(得分:0)

我已经通过在Bootstrap.php文件中编写下面提到的代码解决了这个问题。

protected function _initDbConfig()
{
  $config = new Zend_Config($this->getOptions());
  $params = $config->database->toArray();
  try {
     $db = Zend_Db::factory('Pdo_Mysql', $params);
     $db->getConnection();

  } catch (Zend_Db_Adapter_Exception $e) {
    // perhaps the RDBMS is not running
    // code to send email goes here
  } catch (Zend_Exception $e) {
    // perhaps factory() failed to load the specified Adapter class
    // code to send email goes here         
  }
}

在application.ini中,我有以下代码。

database.host     = "localhost"
database.username = "AAAA"
database.password = "*****"
database.dbname   = "BBBBB"