Fatal Error (如記憶體耗盡、呼叫未定義函式) 會導致腳本立即終止,set_error_handler 無法捕獲 (僅支援 Notice/Warning)。解決方案:使用 register_shutdown_function 搭配 error_get_last()。
error_get_last(),若回傳非 null 且 type === E_ERROR,即為 Fatal Error。function shutdownHandler() {
$error = error_get_last();
if ($error !== null && $error['type'] === E_ERROR) {
// 記錄致命錯誤
error_log("[FATAL] {$error['message']} in {$error['file']}:{$error['line']}");
// 可選:輸出使用者友善頁面 (注意 headers 已送出限制)
// echo '系統發生錯誤,請稍後再試
';
}
}
register_shutdown_function('shutdownHandler');
function shutdownHandler() {
$error = error_get_last();
if ($error === null) return; // 正常結束
$fatalTypes = [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE];
if (in_array($error['type'], $fatalTypes)) {
// 記錄到檔案/資料庫/外部服務
$log = sprintf(
"[%s] %s in %s:%d\nStack: %s",
date('c'),
$error['message'],
$error['file'],
$error['line'],
json_encode(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))
);
file_put_contents('/var/log/php_fatal.log', $log, FILE_APPEND);
}
}
register_shutdown_function('shutdownHandler');
Allowed memory size exhausted) 定位大量資料處理邏輯。error_get_last() 僅回傳最後一個錯誤,多重錯誤可能遺漏。display_errors = Off,瀏覽器仍顯示白畫面,需自行輸出錯誤頁 (在 headers 未送出前)。Throwable 捕獲 Error 例外 (try { ... } catch (Throwable $e) { ... }),涵蓋更完整。