萬盛學電腦網

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

PHP 自動捕獲 Fatal Error (500 錯誤) 並記錄日誌

PHP 發生致命錯誤 (E_ERROR、E_PARSE 等) 時會直接終止腳本,畫面空白且不觸發一般錯誤處理。本文教你用 register_shutdown_function 捕獲並記錄這些錯誤。

核心機制

  • error_get_last():獲取最後發生的錯誤資訊 (型別、訊息、檔案、行號)
  • register_shutdown_function():腳本結束時 (含致命錯誤) 自動執行的回呼

基本實作

<?php
error_reporting(E_ALL);

function handleFatalError() {
    $error = error_get_last();
    
    if ($error === null) return; // 正常結束
    
    // 只處理致命錯誤類型
    $fatalTypes = [
        E_ERROR,           // 1 - 運行時致命錯誤
        E_PARSE,           // 4 - 編譯時解析錯誤
        E_CORE_ERROR,      // 16 - PHP 核心啟動錯誤
        E_COMPILE_ERROR,   // 64 - 編譯錯誤
        E_USER_ERROR,      // 256 - 用戶觸發致命錯誤
        E_RECOVERABLE_ERROR, // 4096 - 可捕獲致命錯誤
    ];
    
    if (!in_array($error['type'], $fatalTypes, true)) {
        return; // 非致命錯誤 (如 Notice、Warning) 已由一般處理器處理
    }
    
    // 格式化錯誤資訊
    $msg = sprintf(
        "[FATAL] %s in %s on line %d\n",
        $error['message'],
        $error['file'],
        $error['line']
    );
    
    // 寫入日誌
    $logFile = __DIR__ . '/logs/fatal_errors.log';
    file_put_contents($logFile, date('Y-m-d H:i:s') . " $msg", FILE_APPEND | LOCK_EX);
    
    // 生產環境:顯示友善頁面而非技術細節
    if (ini_get('display_errors')) {
        echo "

系統發生錯誤

我們已記錄此錯誤,技術人員正在處理中。

"; } else { http_response_code(500); echo "Internal Server Error"; } } register_shutdown_function('handleFatalError'); // 測試觸發 // trigger_error("測試致命錯誤", E_USER_ERROR); // require 'not_exist_file.php'; // E_PARSE 需在編譯階段,這裡只能測試 E_ERROR ?>

進階:完整錯誤處理系統

<?php
class ErrorHandler {
    private string $logDir;
    private bool $isDevelopment;
    
    public function __construct(string $logDir, bool $isDevelopment = false) {
        $this->logDir = $logDir;
        $this->isDevelopment = $isDevelopment;
        
        if (!is_dir($logDir)) mkdir($logDir, 0755, true);
        
        // 註冊處理器
        set_error_handler([$this, 'handleError'], E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);
        set_exception_handler([$this, 'handleException']);
        register_shutdown_function([$this, 'handleShutdown']);
    }
    
    public function handleError(int $level, string $message, string $file, int $line): bool {
        // 不處理 @ 抑制的錯誤
        if (error_reporting() === 0) return false;
        
        $this->logError($level, $message, $file, $line);
        
        // 開發環境顯示詳細錯誤
        if ($this->isDevelopment) {
            $this->displayError($level, $message, $file, $line);
        }
        
        return true; // 阻止內建處理器
    }
    
    public function handleException(Throwable $e): void {
        $this->logError(
            E_ERROR,
            get_class($e) . ": " . $e->getMessage(),
            $e->getFile(),
            $e->getLine(),
            $e->getTraceAsString()
        );
        
        if ($this->isDevelopment) {
            $this->displayException($e);
        } else {
            http_response_code(500);
            echo "系統錯誤,請稍後再試";
        }
    }
    
    public function handleShutdown(): void {
        $error = error_get_last();
        if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR])) {
            $this->handleError($error['type'], $error['message'], $error['file'], $error['line']);
        }
    }
    
    private function logError(int $level, string $message, string $file, int $line, string $trace = ''): void {
        $levelNames = [
            E_ERROR => 'ERROR', E_WARNING => 'WARNING', E_PARSE => 'PARSE',
            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', E_RECOVERABLE_ERROR => 'RECOVERABLE_ERROR', E_DEPRECATED => 'DEPRECATED',
        ];
        
        $log = sprintf(
            "[%s] %s: %s in %s:%d\n%s\n---\n",
            date('Y-m-d H:i:s'),
            $levelNames[$level] ?? 'UNKNOWN',
            $message,
            $file, $line,
            $trace
        );
        
        $logFile = $this->logDir . '/error_' . date('Y-m-d') . '.log';
        file_put_contents($logFile, $log, FILE_APPEND | LOCK_EX);
    }
    
    private function displayError(int $level, string $message, string $file, int $line): void {
        echo "
";
        echo htmlspecialchars("[$level] $message in $file:$line");
        echo "
"; } private function displayException(Throwable $e): void { echo "
";
        echo htmlspecialchars(get_class($e) . ": " . $e->getMessage() . "\n" . $e->getTraceAsString());
        echo "
"; } } // 啟用 (放在入口檔案最開頭) $handler = new ErrorHandler(__DIR__ . '/storage/logs', APP_DEBUG ?? false); ?>

三種顯示錯誤方式對比

方式設定位置優點缺點
php.inidisplay_errors = On/Off全域、不需改代碼需重啟服務、無法動態控制
程式碼 ini_setini_set('display_errors', '1')運行時動態、針對性強需在輸出前、致命錯誤前無效
.htaccess (Apache)php_flag display_errors on目錄級、無需改 PHP僅 Apache、需 AllowOverride

生產環境部署檢查清單

  • ☐ display_errors = Off
  • ☐ log_errors = On
  • ☐ error_log = /var/log/php_errors.log (可寫入)
  • ☐ 註冊 shutdown function 記錄致命錯誤
  • ☐ 自定義 500/404 錯誤頁面 (友善、無敏感資訊)
  • ☐ 日誌輪轉 (logrotate) 防止磁碟爆滿
  • ☐ 錯誤監控告警 (Sentry、ELK、自建)
copyright © 萬盛學電腦網 all rights reserved