How do I catch a PHP fatal (`E_ERROR`) error?(如何捕获 PHP 致命 (`E_ERROR`) 错误?)
问题描述
我可以使用 set_error_handler()
来捕获大多数 PHP 错误,但它不适用于致命 (E_ERROR
) 错误,例如调用不不存在.还有其他方法可以捕获这些错误吗?
I can use set_error_handler()
to catch most PHP errors, but it doesn't work for fatal (E_ERROR
) errors, such as calling a function that doesn't exist. Is there another way to catch these errors?
我正在尝试为所有错误调用 mail()
并且正在运行 PHP 5.2.3.
I am trying to call mail()
for all errors and am running PHP 5.2.3.
推荐答案
使用 register_shutdown_function
记录致命错误,这需要 PHP 5.2+:
Log fatal errors using the register_shutdown_function
, which requires 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
函数.例如:
You will have to define the error_mail
and format_error
functions. For example:
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
函数.
Use Swift Mailer to write the error_mail
function.
另见:
- $php_errormsg
- 预定义常量
这篇关于如何捕获 PHP 致命 (`E_ERROR`) 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何捕获 PHP 致命 (`E_ERROR`) 错误?


基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01