PHP 提供從簡單到完善的多層錯誤處理機制:
set_error_handler() 捕獲運行時錯誤/警告/通知。try/catch/finally + throw new Exception,面向對象、可控制流程。error_log() 記錄、郵件報警。$file = @fopen('welcome.txt', 'r');
if (!$file) {
die('File not found'); // 輸出信息並終止腳本
}
缺點:無法區分錯誤類型、無法恢復、難以記錄上下文。
function customErrorHandler(int $errno, string $errstr, string $errfile = '', int $errline = 0, array $errcontext = []): bool
$errno:錯誤級別常量(E_WARNING、E_NOTICE、E_USER_ERROR 等)。$errstr:錯誤消息。$errfile/$errline:發生位置。$errcontext:當前作用域所有變量(慎用,內存大)。true 表示已處理,**不再執行 PHP 內建處理器**;返回 false 繼續內建處理。| 值 | 常量 | 說明 |
|---|---|---|
| 1 | E_ERROR | 致命運行時錯誤,腳本終止 |
| 2 | E_WARNING | 非致命運行時警告,腳本繼續 |
| 4 | E_PARSE | 編譯時語法解析錯誤 |
| 8 | E_NOTICE | 運行時通知(如未定義變量) |
| 16 | E_CORE_ERROR | PHP 啟動過程致命錯誤 |
| 32 | E_CORE_WARNING | PHP 啟動警告 |
| 64 | E_COMPILE_ERROR | 編譯時致命錯誤 |
| 128 | E_COMPILE_WARNING | 編譯警告 |
| 256 | E_USER_ERROR | 用戶觸發致命錯誤 trigger_error() |
| 512 | E_USER_WARNING | 用戶觸發警告 |
| 1024 | E_USER_NOTICE | 用戶觸發通知 |
| 4096 | E_RECOVERABLE_ERROR | 可捕獲致命錯誤(如類型提示失敗) |
| 8191 | E_ALL | 除 E_STRICT 外所有(PHP 6.0+ 含 E_STRICT) |
function customErrorHandler($errno, $errstr, $errfile, $errline) {
$msg = "[{$errno}] {$errstr} in {$errfile}:{$errline}";
error_log($msg); // 寫入 php.ini error_log 路徑
if ($errno & (E_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)) {
// 致命錯誤:發送郵件、顯示友好頁面、終止
echo "系統錯誤
管理員已收到通知,請稍後重試。
";
exit(1);
}
return true; // 非致命錯誤:已記錄,不再由內建處理
}
set_error_handler('customErrorHandler', E_ALL); // 捕獲所有級別
// 測試觸發
echo $undefinedVar; // E_NOTICE -> 記錄日誌,頁面繼續
trigger_error('業務邏輯異常', E_USER_WARNING); // 記錄日誌
trigger_error('致命業務錯誤', E_USER_ERROR); // 記錄+郵件+終止
trigger_error()if ($age < 0) {
trigger_error('年齡不能為負數', E_USER_WARNING);
}
if ($balance < 0) {
trigger_error('賬戶餘額異常', E_USER_ERROR); // 終止腳本
}
// php.ini 關鍵配置
error_log = /var/log/php/error.log // 文件路徑
; 或 syslog
// 代碼中發送郵件報警(僅用於嚴重錯誤,避免郵件風暴)
error_log("Critical: {$errstr}", 1, 'admin@example.com', 'From: monitor@example.com');
異常用於**可預期、可恢復**的業務邏輯錯誤(驗證失敗、資源不足、API 調用異常)。
try {
$user = $userRepo->findById($id);
if (!$user) {
throw new NotFoundException("User {$id} not found");
}
$order = $orderService->create($user, $items);
} catch (NotFoundException $e) {
// 404 頁面
http_response_code(404);
echo $e->getMessage();
} catch (BusinessException $e) {
// 400 業務錯誤
http_response_code(400);
echo $e->getMessage();
} catch (Throwable $e) { // PHP 7+ 捕獲 Error + Exception
// 500 服務器錯誤,記錄完整堆棧
error_log($e->getMessage() . "\n" . $e->getTraceAsString());
echo '系統繁忙,請稍後重試';
} finally {
// 清理資源(關閉連接、釋放鎖)
$db->close();
}
// 開發環境:顯示所有錯誤
error_reporting(E_ALL);
ini_set('display_errors', '1');
// 生產環境:記錄日誌,不顯示用戶
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', '/var/log/php/error.log');
register_shutdown_function() 捕獲 E_ERROR、E_PARSE 等無法被 set_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])) {
error_log("FATAL: {$error['message']} in {$error['file']}:{$error['line']}");
// 發送郵件、記錄宕機
}
});
error_reporting(E_ALL) + display_errors=On + Xdebug。display_errors=Off + log_errors=On + 統一日誌收集(ELK/Loki)+ 關鍵錯誤郵件/釘釘/企微報警。ValidationException、NotFoundException),控制器統一捕獲轉為 HTTP 響應。finally 或 register_shutdown_function 保證釋放。trigger_error。