單頁應用 (SPA) 運行時間長、狀態複雜,使用者刷新頁面意味著操作重做。捕獲、分析運行時錯誤已成為前端工程必修課。本文系統梳理 try-catch、window.onerror、unhandledrejection 三大捕獲通道,深入解析錯誤物件屬性正規化、堆疊追蹤解析、跨域腳本 Script error. 限制與 CORS 繞過、Source Map 反向映射等進階主題。
// 適用場景:已知可能拋錯的 API、回調函數防護
try {
localStorage.setItem('key', largeData); // 配額超限拋錯
} catch (error) {
reportError(error);
}
// 回調防護:防止回調錯誤阻斷後續邏輯
listeners.forEach(listener => {
try { listener(); }
catch (error) { reportError(error); }
});
// 標準簽名(HTML Living Standard)
window.onerror = function(message, source, lineno, colno, error) {
if (error) {
reportError(error); // 現代瀏覽器提供完整 Error 物件(第5參數)
} else {
reportError({ message, source, lineno, colno }); // 舊瀏覽器降級
}
return true; // 防止瀏覽器預設處理(部分瀏覽器)
};
⚠️ 不要用 addEventListener('error', ...) 監聽 window.onerror,標準只定義 onerror 屬性。
window.addEventListener('unhandledrejection', function(event) {
reportError(event.reason); // reason 通常是 Error 物件
event.preventDefault(); // 防止瀏覽器預設警告
});
各瀏覽器 Error 物件屬性命名不一致:
| 標準屬性 | Chrome | Firefox | Safari | Edge/IE |
|---|---|---|---|---|
| message | message | message | message | message |
| name | name | name | name | name |
| stack | stack | stack | stack | stack |
| 檔案/腳本 | script / filename | fileName / sourceURL | sourceURL | script |
| 行號 | line / lineno | lineNumber / lineno | line | line |
| 列號 | column / colno | columnNumber / colno | column | column |
function normalizeError(error) {
const normalized = {
name: error.name || 'Error',
message: error.message || String(error),
stack: error.stack || '',
};
// 檔案路徑正規化
normalized.file = error.fileName || error.sourceURL || error.script || '';
normalized.line = error.lineNumber || error.lineno || error.line || 0;
normalized.column = error.columnNumber || error.colno || error.column || 0;
return normalized;
}
各瀏覽器 stack 字串格式不同:
at FunctionName (file:line:col)FunctionName@file:line:colFunctionName@file:line// 簡易解析器範例
const STACK_FRAME_REGEX = {
chrome: /at\s+(.+?)\s+\((?:(.+?):(\d+):(\d+)|(.+?):(\d+):(\d+))\)/,
firefox: /(.+)@(.+):(\d+):(\d+)/,
safari: /(.+)@(.+):(\d+)/
};
function parseStack(stack) {
// 實作省略:需維護正則映射表,提取 function、file、line、column
return frames; // [{function, file, line, column}, ...]
}
Script error. 之謎原因:瀏覽器安全策略,不同源腳本拋出的錯誤被過濾,只剩 Script error.,堆疊、檔案、行號全丟失。
Access-Control-Allow-Origin: * (或特定域名)<script src="https://cdn.example.com/app.js" crossorigin="anonymous"></script>滿足兩條件後,跨域錯誤將包含完整資訊。
生產環境代碼經壓縮、混淆、打包,行號失真。Source Map 映射 (生成碼行, 生成碼列) → (源碼行, 源碼列, 源檔案)。
// 假設打包時每檔案分配 1000 行區間
// step1.js: 1-1000, step2.js: 1001-2000, step3.js: 2001-3000
function mapLineToSource(bundleLine) {
if (bundleLine <= 1000) return { file: 'step1.js', line: bundleLine };
if (bundleLine <= 2000) return { file: 'step2.js', line: bundleLine - 1000 };
if (bundleLine <= 3000) return { file: 'step3.js', line: bundleLine - 2000 };
return { file: 'unknown', line: bundleLine };
}
// 實際專案用 source-map 庫
const sourceMap = require('source-map');
const consumer = await new sourceMap.SourceMapConsumer(rawSourceMap);
const original = consumer.originalPositionFor({ line: bundleLine, column: bundleColumn });
// original: { source: 'src/step3.js', line: 5, column: 10, name: 'handler' }
// 1. 統一入口
function reportError(error) {
const normalized = normalizeError(error);
const enriched = enrichContext(normalized); // 加入用戶、版本、URL、UserAgent
const parsed = parseStack(enriched.stack); // 解析堆疊
const mapped = mapToSource(parsed); // Source Map 映射
sendToServer(mapped); // 批量上報
}
// 2. 批量發送,避免阻塞
const queue = [];
setInterval(() => {
if (queue.length) {
navigator.sendBeacon('/api/errors', JSON.stringify(queue.splice(0)));
}
}, 5000);
window.onerror + unhandledrejectiontry-catch 防護crossorigin建立完善的錯誤觀測體系,是前端工程化邁向成熟的關鍵一步。