set_error_handler 捕獲不到?set_error_handler 僅能處理 E_WARNING、E_NOTICE 等非致命錯誤。E_ERROR、E_PARSE、E_CORE_ERROR 等致命錯誤會直接終止腳本,無法被用戶級處理器攔截。
register_shutdown_function + error_get_last()<?php
function fatalErrorHandler() {
$error = error_get_last();
if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
// 記錄日誌、發送告警、友好提示
$msg = "[FATAL] {$error['message']} in {$error['file']}:{$error['line']}";
error_log($msg);
// 生產環境可發郵件/釘釘/企微通知運維
// mail('admin@example.com', 'PHP Fatal Error', $msg);
echo "系統繁忙,請稍後重試
"; // 用戶友好頁面
}
}
register_shutdown_function('fatalErrorHandler');
// 測試觸發
// require 'not_exist_file.php'; // E_COMPILE_ERROR
// $obj = new NonExistentClass(); // E_ERROR
register_shutdown_function 註冊的回調在腳本**正常結束**或**致命錯誤終止**時均會執行。error_get_last() 返回最後發生的錯誤信息(含 type、message、file、line)。set_error_handler 處理的警告/通知。die()/exit()、throw Exception、header()(已發送輸出),只能記錄日誌與輸出友好頁面。set_exception_handler(function($e) {
error_log("[EXCEPTION] {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}");
echo "服務異常
";
});
set_error_handler(function($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) return false; // 未在報告範圍內
throw new ErrorException($message, 0, $severity, $file, $line);
});
register_shutdown_function('fatalErrorHandler');
實現「異常化錯誤、錯誤異常化、致命錯誤統一收口」的完整錯誤處理體系。