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_ERROR | 1 | 致命運行時錯誤,腳本終止 | 否(需 shutdown_function) |
| E_WARNING | 2 | 運行時警告,腳本繼續 | 是 |
| E_PARSE | 4 | 編譯時解析錯誤 | 否 |
| E_NOTICE | 8 | 運行時提示(如未定義變數) | 是 |
| E_USER_ERROR | 256 | 用戶觸發的致命錯誤 | 是 |
| E_USER_WARNING | 512 | 用戶觸發的警告 | 是 |
| E_USER_NOTICE | 1024 | 用戶觸發的提示 | 是 |
| E_RECOVERABLE_ERROR | 4096 | 可捕獲的致命錯誤(如類型提示失敗) | 是 |
| E_ALL | 32767 | 所有錯誤(除 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()}";
}
?>
自定義錯誤處理是構建健壯 PHP 應用的基石。核心原則:開發環境盡早暴露問題,生產環境完整記錄並優雅降級。結合 `set_error_handler`、`set_exception_handler`、`register_shutdown_function` 三大機制,可實現全方位的錯誤捕獲與處理。現代框架(Laravel、Symfony)已內建完善的錯誤處理組件,建議直接使用框架提供的機制擴展而非重複造輪子。