php - 如何捕获 PHP 致命 (`E_ERROR` ) 错误?

我可以使用 set_error_handler() 来捕获大多数 PHP 错误,但它不适用于致命 (E_ERROR) 错误,例如调用一个没有不存在。还有其他方法可以捕获这些错误吗?

我正在尝试为所有错误调用 mail() 并且正在运行 PHP 5.2.3。

最佳答案

使用 register_shutdown_function 记录 fatal error ,这需要 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_mailformat_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
  • Predefined Constants

https://stackoverflow.com/questions/277224/

相关文章:

php - 可以使用 PHP 短标签吗?

php - 新 self 与新静态

php - 是否有将 PHP 数组复制到另一个数组的功能?

php - 在 PHP 中将整数转换为字符串

php - 不能在写上下文中使用方法返回值

php - htmlentities() 与 htmlspecialchars()

php - PHP 中的 HTTP_HOST 和 SERVER_NAME 有什么区别?

php - 如何在 PHP 中执行静态代码分析?

php - 更改最大上传文件大小

php - 按一个属性对对象数组进行排序