王新阳

wangxinyang

php获取程序异常(普通错误和致命错误)

<?php
/**
 * PHP 全局错误接管模块
 * 放置于入口文件最顶部
 */

// 1. 基础配置:关闭默认显示,开启内部报告
ini_set('display_errors', '0'); // 生产环境务必为 0,测试时可设为 1 辅助调试
ini_set('log_errors', '1');
error_reporting(E_ALL);

// 模拟数据库连接或日志路径(实际项目中请替换为你的真实配置)
define('LOG_FILE', __DIR__ . '/runtime/error.log'); 
// 如果需要写入数据库,请在此处引入你的 DB 类或 PDO 连接
// $pdo = new PDO(...); 

/**
 * 统一错误处理核心函数
 * @param int    $errno   错误级别
 * @param string $errstr  错误信息
 * @param string $errfile 错误文件
 * @param int    $errline 错误行号
 */
function globalErrorHandler($errno, $errstr, $errfile, $errline) {
    // 忽略被 @ 抑制的错误
    if (!(error_reporting() & $errno)) {
        return false;
    }

    $errorTypeMap = [
        E_ERROR             => 'FATAL ERROR',
        E_WARNING           => 'WARNING',
        E_PARSE             => 'PARSE ERROR',
        E_NOTICE            => 'NOTICE',
        E_CORE_ERROR        => 'CORE ERROR',
        E_COMPILE_ERROR     => 'COMPILE ERROR',
        E_USER_ERROR        => 'USER ERROR',
        E_USER_WARNING      => 'USER WARNING',
        E_USER_NOTICE       => 'USER NOTICE',
        E_STRICT            => 'STRICT NOTICE',
        E_RECOVERABLE_ERROR => 'RECOVERABLE ERROR',
        E_DEPRECATED        => 'DEPRECATED',
    ];

    $level = $errorTypeMap[$errno] ?? 'UNKNOWN';
    $time  = date('Y-m-d H:i:s');
    
    // 构建详细错误信息
    $message = sprintf(
        "[%s] %s: %s in %s on line %d",
        $time, $level, $errstr, $errfile, $errline
    );

    // --- 动作 A: 记录到本地文件 (最稳妥的兜底) ---
    error_log($message . PHP_EOL, 3, LOG_FILE);

    // --- 动作 B: 写入数据库 (可选,需确保 DB 连接可用) ---
    /*
    try {
        global $pdo; // 假设全局存在 PDO 连接
        $stmt = $pdo->prepare("INSERT INTO system_logs (level, message, file_path, line_number, created_at) VALUES (?, ?, ?, ?, NOW())");
        $stmt->execute([$level, $errstr, $errfile, $errline]);
    } catch (Exception $e) {
        // 如果 DB 写入失败,至少保证文件日志已记录,避免死循环
        error_log("DB Log Failed: " . $e->getMessage(), 3, LOG_FILE);
    }
    */

    // --- 动作 C: 页面输出 (仅针对非致命错误或测试环境) ---
    // 如果是致命错误,脚本即将终止,这里输出可能无效,主要靠 Shutdown 函数
    if (in_array($errno, [E_USER_ERROR, E_USER_WARNING, E_WARNING, E_NOTICE])) {
        echo "<div style='color:red; border:1px solid red; padding:10px; margin:10px;'>";
        echo "<strong>System Error:</strong> " . htmlspecialchars($errstr) . "<br>";
        echo "<small>File: " . htmlspecialchars($errfile) . " Line: " . $errline . "</small>";
        echo "</div>";
    }

    // 返回 true 表示已处理,阻止 PHP 默认的错误输出
    return true;
}

/**
 * 致命错误捕获函数 (Shutdown Function)
 * 用于捕获 E_ERROR, E_PARSE 等导致脚本立即终止的错误
 */
function globalShutdownHandler() {
    $error = error_get_last();
    
    // 判断是否发生了致命错误
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR])) {
        $time  = date('Y-m-d H:i:s');
        $level = 'FATAL SHUTDOWN';
        $message = sprintf(
            "[%s] %s: %s in %s on line %d",
            $time, $level, $error['message'], $error['file'], $error['line']
        );

        // 记录到文件
        error_log($message . PHP_EOL, 3, LOG_FILE);

        // 写入数据库逻辑同上...

        // 向浏览器输出友好提示(如果 headers 未发送)
        if (!headers_sent()) {
            http_response_code(500);
            echo "<div style='color:red; text-align:center; margin-top:50px;'>";
            echo "<h1>系统发生严重错误</h1>";
            echo "<p>错误信息已记录,请联系管理员。</p>";
            echo "<!-- Debug Info: " . htmlspecialchars($error['message']) . " -->"; // 测试时可打开注释
            echo "</div>";
        }
    }
}

/**
 * 全局异常捕获函数
 * 用于捕获未处理的 Exception 和 PHP 7+ 的 Error (如 TypeError)
 */
function globalExceptionHandler($throwable) {
    $time  = date('Y-m-d H:i:s');
    $class = get_class($throwable);
    $message = sprintf(
        "[%s] Uncaught %s: %s in %s on line %d\nStack Trace:\n%s",
        $time, $class, $throwable->getMessage(), $throwable->getFile(), $throwable->getLine(), $throwable->getTraceAsString()
    );

    // 记录日志
    error_log($message . PHP_EOL, 3, LOG_FILE);
    
    // 写入数据库逻辑同上...

    // 页面输出
    if (!headers_sent()) {
        http_response_code(500);
        echo "<div style='color:red; border:1px solid red; padding:10px; margin:10px;'>";
        echo "<strong>Uncaught Exception:</strong> " . htmlspecialchars($throwable->getMessage()) . "<br>";
        echo "<small>" . htmlspecialchars($throwable->getFile()) . ":" . $throwable->getLine() . "</small>";
        echo "</div>";
    }
}

// 2. 注册处理器
set_error_handler('globalErrorHandler');       // 接管普通错误
register_shutdown_function('globalShutdownHandler'); // 接管致命错误
set_exception_handler('globalExceptionHandler');     // 接管未捕获异常

// --- 测试代码 (正式使用时请删除) ---
// 1. 测试普通警告
// echo $undefinedVar; 

// 2. 测试致命错误 (取消注释测试)
// require 'non_existent_file.php';

// 3. 测试异常
// throw new Exception("Test Exception");

使用说明

  1. ‌放置位置‌:将此代码块放在你项目唯一的入口文件(如 index.php)的‌第一行‌(<?php 之后)。
  2. ‌日志路径‌:修改 LOG_FILE 常量为你服务器上有写入权限的路径。
  3. ‌数据库集成‌:如果希望写入数据库,取消注释“动作 B”部分的代码,并确保 $pdo 对象在处理错误时依然可用(注意:在致命错误 Shutdown 阶段,数据库连接可能已断开,建议优先使用文件日志或 Redis 队列)。
  4. ‌测试与生产切换‌:
    • ‌测试时‌:保持 ini_set('display_errors', '0'),依靠代码中的 echo 输出查看详细错误,同时查看 runtime/error.log。
    • ‌生产时‌:注释掉代码中所有 echo 输出的部分,只保留日志记录,防止敏感路径泄露。

为什么这样能接管“所有”错误?

  • ‌set_error_handler‌:捕获 Warning, Notice, User Error 等非致命运行时错误。
  • ‌set_exception_handler‌:捕获所有未被 try-catch 处理的 Exception 以及 PHP 7+ 的 Error(如 TypeError, Call to undefined method)。
  • ‌register_shutdown_function‌:这是最后一道防线。当发生 Parse Error(语法错误)或 Memory Limit Exceeded(内存溢出)时,脚本会立即终止,前两个处理器无法执行,但 Shutdown 函数一定会运行,通过 error_get_last() 获取最后的致命错误信息。

2026-07-29
2026-11-28 星期六 农历十月二十