萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 自定義錯誤處理機制完整指南:set_error_handler 實戰應用

為什麼需要自定義錯誤處理?

  • 統一錯誤日誌格式,便於監控系統收集分析
  • 區分環境:開發環境顯示詳情,生產環境記錄日誌並顯示友好頁面
  • 捕獲致命錯誤(E_ERROR)前的最後機會進行清理或通知
  • 將錯誤轉換為異常,統一使用 try-catch 處理流程

核心函數:set_error_handler()

set_error_handler(callable $callback, int $error_levels = E_ALL): callable|false
  • $callback:處理函數,簽名 `handler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext): bool`
  • $error_levels:要攔截的錯誤級別位掩碼,預設 `E_ALL`
  • 返回值:之前的錯誤處理器(可用於鏈式調用或恢復)

完整實作範例

<?php
declare(strict_types=1);

// 1. 定義錯誤級別標籤映射
const ERROR_LABELS = [
    E_ERROR             => 'Fatal Error',
    E_WARNING           => 'Warning',
    E_PARSE             => 'Parse Error',
    E_NOTICE            => 'Notice',
    E_CORE_ERROR        => 'Core Error',
    E_CORE_WARNING      => 'Core Warning',
    E_COMPILE_ERROR     => 'Compile Error',
    E_COMPILE_WARNING   => 'Compile Warning',
    E_USER_ERROR        => 'User Error',
    E_USER_WARNING      => 'User Warning',
    E_USER_NOTICE       => 'User Notice',
    E_STRICT            => 'Strict Standards',
    E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
    E_DEPRECATED        => 'Deprecated',
    E_USER_DEPRECATED   => 'User Deprecated',
];

// 2. 自定義錯誤處理器
function customErrorHandler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext = []): bool {
    // 不處理被 @ 運算符抑制的錯誤
    if (error_reporting() === 0) {
        return false; // 交給內建處理器
    }

    $label = ERROR_LABELS[$errno] ?? 'Unknown Error';
    $timestamp = date('Y-m-d H:i:s');
    
    // 構建結構化日誌數據
    $logData = [
        'timestamp' => $timestamp,
        'level' => $label,
        'code' => $errno,
        'message' => $errstr,
        'file' => $errfile,
        'line' => $errline,
        'trace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5),
        'context' => array_keys($errcontext), // 僅記錄變數名,避免敏感數據/大對象
    ];

    // 3. 根據級別決定行為
    $isFatal = in_array($errno, [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR], true);
    $isWarning = in_array($errno, [E_WARNING, E_CORE_WARNING, E_COMPILE_WARNING, E_USER_WARNING, E_RECOVERABLE_ERROR], true);
    $isNotice = in_array($errno, [E_NOTICE, E_USER_NOTICE, E_STRICT, E_DEPRECATED, E_USER_DEPRECATED], true);

    // 生產環境:記錄日誌,不顯示細節
    $isProduction = (getenv('APP_ENV') ?? 'development') === 'production';
    
    if ($isProduction) {
        // 寫入日誌文件或發送到日誌服務
        error_log(json_encode($logData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n", 3, __DIR__ . '/logs/php_errors.log');
        
        if ($isFatal) {
            // 致命錯誤:顯示友好錯誤頁,發送告警
            http_response_code(500);
            include __DIR__ . '/templates/500.php';
            // 可在此發送郵件/Slack/钉钉告警
            exit(1);
        }
        // 非致命:靜默記錄,不中斷腳本
        return true; // 表示已處理,不再傳給內建處理器
    } 
    
    // 開發環境:直接輸出詳細信息
    $output = "[{$timestamp}] {$label}: {$errstr} in {$errfile} on line {$errline}\n";
    $output .= "Stack trace:\n" . implode("\n", array_map(function($frame) {
        $file = $frame['file'] ?? 'unknown';
        $line = $frame['line'] ?? '?';
        $func = ($frame['class'] ?? '') . ($frame['type'] ?? '') . ($frame['function'] ?? '');
        return "  # {$file}:{$line} in {$func}()";
    }, $logData['trace']));
    
    if (PHP_SAPI === 'cli') {
        fwrite(STDERR, $output . "\n");
    } else {
        // 網頁環境美化輸出
        echo "
";
        echo htmlspecialchars($output);
        echo "
"; } // 致命錯誤在開發環境也中斷 if ($isFatal) exit(1); return true; // 阻止內建處理器重複輸出 } // 4. 註冊處理器 set_error_handler('customErrorHandler'); // 可選:註冊異常處理器統一捕獲未捕獲異常 set_exception_handler(function(Throwable $e) { customErrorHandler(E_ERROR, $e->getMessage(), $e->getFile(), $e->getLine()); }); // 可選:註冊關閉函數捕獲致命錯誤(E_ERROR 等無法被 error_handler 捕獲) register_shutdown_function(function() { $error = error_get_last(); if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) { customErrorHandler($error['type'], $error['message'], $error['file'], $error['line']); } }); // ==================== 測試演示 ==================== echo "<h2>自定義錯誤處理測試</h2>"; // 觸發各類錯誤 trigger_error('這是一個用戶通知', E_USER_NOTICE); trigger_error('這是一個用戶警告', E_USER_WARNING); trigger_error('這是一個用戶錯誤', E_USER_ERROR); // 會中斷腳本 // 以下代碼不會執行 echo "這行不會顯示"; ?>

錯誤級別常量速查表

常量值描述可被捕獲
E_ERROR1致命運行時錯誤,腳本終止否(需 shutdown_function)
E_WARNING2運行時警告,腳本繼續是
E_PARSE4編譯時解析錯誤否
E_NOTICE8運行時提示(如未定義變數)是
E_USER_ERROR256用戶觸發的致命錯誤是
E_USER_WARNING512用戶觸發的警告是
E_USER_NOTICE1024用戶觸發的提示是
E_RECOVERABLE_ERROR4096可捕獲的致命錯誤(如類型提示失敗)是
E_ALL32767所有錯誤(除 E_STRICT 在 5.4 前)-

進階模式:錯誤轉異常

<?php
class ErrorException extends Exception {
    public function __construct(int $code, string $message, string $file, int $line) {
        parent::__construct($message, $code);
        $this->file = $file;
        $this->line = $line;
    }
}

function errorToExceptionHandler(int $errno, string $errstr, string $errfile, int $errline): bool {
    if (error_reporting() === 0) return false; // 尊重 @
    throw new ErrorException($errno, $errstr, $errfile, $errline);
}

set_error_handler('errorToExceptionHandler');

// 現在可以用 try-catch 統一處理錯誤與異常
try {
    $result = 10 / 0; // E_WARNING
    $arr = []; echo $arr['key']; // E_NOTICE
} catch (ErrorException $e) {
    echo "捕獲轉換後的異常: [{$e->getCode()}] {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}";
}
?>

生產環境部署清單

  1. 設置 `display_errors = Off`、`log_errors = On`、`error_log = /var/log/php/error.log`
  2. 設置 `error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT`(或按需)
  3. 確保日誌目錄可寫,配置 logrotate 定期輪轉
  4. 接入日誌聚合系統(ELK、Loki、Sentry 等)
  5. 配置告警規則:E_ERROR/E_USER_ERROR 立即告警,E_WARNING 聚合告警
  6. 準備友好的 500/503 錯誤頁面模板

總結

自定義錯誤處理是構建健壯 PHP 應用的基石。核心原則:開發環境盡早暴露問題,生產環境完整記錄並優雅降級。結合 `set_error_handler`、`set_exception_handler`、`register_shutdown_function` 三大機制,可實現全方位的錯誤捕獲與處理。現代框架(Laravel、Symfony)已內建完善的錯誤處理組件,建議直接使用框架提供的機制擴展而非重複造輪子。

copyright © 萬盛學電腦網 all rights reserved