萬盛學電腦網

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

PHP 自訂錯誤處理器:將錯誤資訊郵件通知開發人員

使用 set_error_handler() 註冊自訂處理函數,捕獲錯誤並以 HTML 郵件發送給開發人員,包含錯誤編號、訊息、檔案、行號、當時變數快照,嚴重錯誤則終止腳本。

實作程式碼

<?php
function nettuts_error_handler($number, $message, $file, $line, $vars) {
    $email = "<h3>An error ($number) occurred</h3>";
    $email .= "<p><strong>File:</strong> $file<br>";
    $email .= "<strong>Line:</strong> $line</p>";
    $email .= "<p><strong>Message:</strong> $message</p>";
    $email .= "<pre>" . print_r($vars, true) . "</pre>";

    $headers = "Content-type: text/html; charset=utf-8\r\n";
    error_log($email, 1, 'developer@example.com', $headers);

    // 非 E_NOTICE 且非使用者定義錯誤(<2048)則終止
    if ($number !== E_NOTICE && $number < 2048) {
        die('系統發生錯誤,請稍後再試。');
    }
}
set_error_handler('nettuts_error_handler');

// 測試觸發
echo $undefined_var; // 產生 Notice
?>

關鍵點

  • error_log(..., 1, $email, $headers) 第 2 參數 1 表示寄送郵件。
  • print_r($vars, true) 回傳當時所有區域變數內容,利於除錯。
  • 生產環境建議搭配 error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT) 避免雜訊。
  • 嚴重錯誤(E_ERROR、E_PARSE 等)無法被自訂處理器捕獲,需配合 register_shutdown_function() 檢查 error_get_last()。
copyright © 萬盛學電腦網 all rights reserved