如何集中处理php错误和异常 [英] How to handle php errors and exceptions centrally
问题描述
以前在PHP 4中,我创建了一个自定义错误处理程序(如下)来处理我自己的触发错误和一般的PHP错误。但是现在PHP 5引入了异常,即我正在利用PDO进行数据库操作,并且不确定如何处理一般的PHP错误和这些异常吗?
previously in PHP 4 i created a custom error handler (below) to handle my own triggered errors and general PHP errors. But now PHP 5 introduces Exceptions i.e. I'm leveraging PDO for database manipulation and I'm not sure how to handle both general PHP errors and these Exceptions?
function errorHandler($errno, $errstr, $errfile, $errline){
switch ($errno) {
case E_USER_ERROR:
// Send an e-mail to the administrator
error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
// Write the error to our log file
error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
break;
case E_USER_WARNING:
// Write the error to our log file
error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
case E_USER_NOTICE:
// Write the error to our log file
error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
default:
// Write the error to our log file
error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
break;
}
// Don't execute PHP's internal error handler
return TRUE;
}
推荐答案
您可以使用 set_exception_handler( )
处理自定义函数中未捕获的异常。
You can use set_exception_handler()
to deal with uncaught exceptions in your custom function.
但是,正确的方法是让您 try ... catch
例外,例如进行查询,并使用您的自定义函数对其进行相应记录。
The "right" way, however, would be for you to try ... catch
the exception when e.g. doing a query, and use your custom function to log it accordingly.
这篇关于如何集中处理php错误和异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!