如何捕获 PHP 致命(“E_ERROR”)错误?
2022-08-30 05:50:01
我可以用来捕获大多数PHP错误,但它不适用于致命()错误,例如调用不存在的函数。有没有另一种方法可以捕获这些错误?set_error_handler()
E_ERROR
我正在尝试调用所有错误,并且正在运行PHP 5.2.3。mail()
我可以用来捕获大多数PHP错误,但它不适用于致命()错误,例如调用不存在的函数。有没有另一种方法可以捕获这些错误?set_error_handler()
E_ERROR
我正在尝试调用所有错误,并且正在运行PHP 5.2.3。mail()
使用 记录致命错误,这需要 PHP 5.2+:register_shutdown_function
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 5.2.0 +):
function shutDownFunction() {
$error = error_get_last();
// Fatal error, E_ERROR === 1
if ($error['type'] === E_ERROR) {
// Do your stuff
}
}
register_shutdown_function('shutDownFunction');
预定义的常量中定义了不同的错误类型。