我可以使用set_error_handler()来捕获大多数PHP错误,但它不适用于致命(E_ERROR)错误,例如调用不存在的函数。是否有其他方法来捕捉这些错误?
我试图调用mail()为所有错误和运行PHP 5.2.3。
我可以使用set_error_handler()来捕获大多数PHP错误,但它不适用于致命(E_ERROR)错误,例如调用不存在的函数。是否有其他方法来捕捉这些错误?
我试图调用mail()为所有错误和运行PHP 5.2.3。
当前回答
PHP有可捕获的致命错误。它们被定义为E_RECOVERABLE_ERROR。PHP手册将E_RECOVERABLE_ERROR描述为:
可捕捉的致命错误。它表示可能发生了危险的错误,但没有使引擎处于不稳定状态。如果用户定义的句柄没有捕捉到错误(参见set_error_handler()),应用程序将中止,因为它是一个E_ERROR。
您可以通过使用set_error_handler()并检查E_RECOVERABLE_ERROR来“捕获”这些“致命”错误。我发现当这个错误被捕获时抛出一个异常很有用,然后你可以使用try/catch。
这个问题和答案提供了一个有用的例子:如何在PHP类型提示中捕获“可捕获的致命错误”?
然而,E_ERROR错误可以处理,但不能恢复,因为引擎处于不稳定状态。
其他回答
使用register_shutdown_function记录致命错误,这需要PHP 5.2+:
register_shutdown_function( "fatal_handler" );
function fatal_handler() {
$errfile = "unknown file";
$errstr = "shutdown";
$errno = E_CORE_ERROR;
$errline = 0;
$error = error_get_last();
if($error !== NULL) {
$errno = $error["type"];
$errfile = $error["file"];
$errline = $error["line"];
$errstr = $error["message"];
error_mail(format_error( $errno, $errstr, $errfile, $errline));
}
}
必须定义error_mail和format_error函数。例如:
function format_error( $errno, $errstr, $errfile, $errline ) {
$trace = print_r( debug_backtrace( false ), true );
$content = "
<table>
<thead><th>Item</th><th>Description</th></thead>
<tbody>
<tr>
<th>Error</th>
<td><pre>$errstr</pre></td>
</tr>
<tr>
<th>Errno</th>
<td><pre>$errno</pre></td>
</tr>
<tr>
<th>File</th>
<td>$errfile</td>
</tr>
<tr>
<th>Line</th>
<td>$errline</td>
</tr>
<tr>
<th>Trace</th>
<td><pre>$trace</pre></td>
</tr>
</tbody>
</table>";
return $content;
}
使用Swift Mailer编写error_mail函数。
参见:
php_errormsg美元 预定义常量
我需要处理生产的致命错误,而不是显示静态样式的503服务不可用HTML输出。这无疑是“捕捉致命错误”的合理方法。这就是我所做的:
我有一个自定义错误处理函数“error_handler”,它将在任何E_ERROR, E_USER_ERROR等上显示我的“503服务不可用”HTML页面。这将被shutdown函数调用,捕捉致命错误,
function fatal_error_handler() {
if (@is_array($e = @error_get_last())) {
$code = isset($e['type']) ? $e['type'] : 0;
$msg = isset($e['message']) ? $e['message'] : '';
$file = isset($e['file']) ? $e['file'] : '';
$line = isset($e['line']) ? $e['line'] : '';
if ($code>0)
error_handler($code, $msg, $file, $line);
}
}
set_error_handler("error_handler");
register_shutdown_function('fatal_error_handler');
在我的自定义error_handler函数中,如果错误是E_ERROR, E_USER_ERROR等。我还调用@ob_end_clean();清空缓冲区,从而删除PHP的“致命错误”消息。
请注意严格的isset()检查和@ silence函数,因为我们不希望error_handler脚本生成任何错误。
在仍然同意keparo的情况下,捕获致命错误确实没有达到“致命错误”的目的,因此它实际上并不打算让您做进一步的处理。在此关闭过程中不要运行任何mail()函数,因为您肯定会备份邮件服务器或收件箱。而是将这些事件记录到文件中,并安排一个cron作业来查找这些error.log文件并将它们发送给管理员。
好吧,似乎可以用其他方式捕获致命错误:)
ob_start('fatal_error_handler');
function fatal_error_handler($buffer){
$error = error_get_last();
if($error['type'] == 1){
// Type, message, file, line
$newBuffer='<html><header><title>Fatal Error </title></header>
<style>
.error_content{
background: ghostwhite;
vertical-align: middle;
margin:0 auto;
padding: 10px;
width: 50%;
}
.error_content label{color: red;font-family: Georgia;font-size: 16pt;font-style: italic;}
.error_content ul li{ background: none repeat scroll 0 0 FloralWhite;
border: 1px solid AliceBlue;
display: block;
font-family: monospace;
padding: 2%;
text-align: left;
}
</style>
<body style="text-align: center;">
<div class="error_content">
<label >Fatal Error </label>
<ul>
<li><b>Line</b> ' . $error['line'] . '</li>
<li><b>Message</b> ' . $error['message'] . '</li>
<li><b>File</b> ' . $error['file'] . '</li>
</ul>
<a href="javascript:history.back()"> Back </a>
</div>
</body></html>';
return $newBuffer;
}
return $buffer;
}
在Zend Framework 2中找到了很好的解决方案:
/**
* ErrorHandler that can be used to catch internal PHP errors
* and convert to an ErrorException instance.
*/
abstract class ErrorHandler
{
/**
* Active stack
*
* @var array
*/
protected static $stack = array();
/**
* Check if this error handler is active
*
* @return bool
*/
public static function started()
{
return (bool) static::getNestedLevel();
}
/**
* Get the current nested level
*
* @return int
*/
public static function getNestedLevel()
{
return count(static::$stack);
}
/**
* Starting the error handler
*
* @param int $errorLevel
*/
public static function start($errorLevel = \E_WARNING)
{
if (!static::$stack) {
set_error_handler(array(get_called_class(), 'addError'), $errorLevel);
}
static::$stack[] = null;
}
/**
* Stopping the error handler
*
* @param bool $throw Throw the ErrorException if any
* @return null|ErrorException
* @throws ErrorException If an error has been catched and $throw is true
*/
public static function stop($throw = false)
{
$errorException = null;
if (static::$stack) {
$errorException = array_pop(static::$stack);
if (!static::$stack) {
restore_error_handler();
}
if ($errorException && $throw) {
throw $errorException;
}
}
return $errorException;
}
/**
* Stop all active handler
*
* @return void
*/
public static function clean()
{
if (static::$stack) {
restore_error_handler();
}
static::$stack = array();
}
/**
* Add an error to the stack
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @return void
*/
public static function addError($errno, $errstr = '', $errfile = '', $errline = 0)
{
$stack = & static::$stack[count(static::$stack) - 1];
$stack = new ErrorException($errstr, 0, $errno, $errfile, $errline, $stack);
}
}
这个类允许您在需要时启动特定的ErrorHandler。然后你也可以停止处理程序。
使用这个类,例如:
ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();
if ($innerException = ErrorHandler::stop()) {
throw new Exception('Special Exception Text', 0, $innerException);
}
// or
ErrorHandler::stop(true); // directly throws an Exception;
链接到完整的类代码:https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/ErrorHandler.php
一个更好的解决方案是独白: 链接到完整的类代码:https://github.com/Seldaek/monolog/blob/master/src/Monolog/ErrorHandler.php
它还可以使用register_shutdown_function函数处理FATAL_ERRORS。根据这个类,FATAL_ERROR是以下数组之一(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR)。
class ErrorHandler
{
// [...]
public function registerExceptionHandler($level = null, $callPrevious = true)
{
$prev = set_exception_handler(array($this, 'handleException'));
$this->uncaughtExceptionLevel = $level;
if ($callPrevious && $prev) {
$this->previousExceptionHandler = $prev;
}
}
public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
{
$prev = set_error_handler(array($this, 'handleError'), $errorTypes);
$this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
if ($callPrevious) {
$this->previousErrorHandler = $prev ?: true;
}
}
public function registerFatalHandler($level = null, $reservedMemorySize = 20)
{
register_shutdown_function(array($this, 'handleFatalError'));
$this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
$this->fatalLevel = $level;
}
// [...]
}
下面是一个获取当前error_handler method =)的小技巧
<?php
register_shutdown_function('__fatalHandler');
function __fatalHandler()
{
$error = error_get_last();
// Check if it's a core/fatal error. Otherwise, it's a normal shutdown
if($error !== NULL && $error['type'] === E_ERROR) {
// It is a bit hackish, but the set_exception_handler
// will return the old handler
function fakeHandler() { }
$handler = set_exception_handler('fakeHandler');
restore_exception_handler();
if($handler !== null) {
call_user_func(
$handler,
new ErrorException(
$error['message'],
$error['type'],
0,
$error['file'],
$error['line']));
}
exit;
}
}
?>
我还想提醒你,如果你打电话来
<?php
ini_set('display_errors', false);
?>
PHP停止显示错误。否则,错误文本将先于错误处理程序发送给客户端。