Featured image of post 前端错误监控:从 window.onerror 到 SourceMap 还原

前端错误监控:从 window.onerror 到 SourceMap 还原

搭建一套能真正定位问题的前端监控:三类错误的捕获方式、错误归一化与去重降噪、SourceMap 在生产环境的还原策略、以及那些不该上报的异常白名单。

31 次

问题现场

线上收到用户反馈:「点了保存没反应。」

问用户什么机型、什么浏览器,用户答不上来。开 Chrome 控制台复现 —— 好的,页面正常。

打开监控平台,发现过去 7 天前端错误率是 0.2%,但没有任何具体的错误记录。日志里只有一行被截断的:

Uncaught TypeError: Cannot read properties of null (reading 'id')

没有堆栈,没有文件行号,没有用户上下文。

这就是没做监控的典型状态:知道出错了,但不知道错在哪。

前端有三类错误,处理方式完全不同

这是最容易混淆的地方 —— 三类错误的捕获手段和可用信息都不一样。

1. 同步错误 —— try/catch 能抓到
   window.onerror / try-catch / Error Boundary
   特点:调用栈完整,try-catch 拿得到堆栈

2. 异步错误 —— setTimeout / Promise 里的错误
   window.onerror 能抓 Promise 的 unhandledrejection
   但 fetch.then() 里的错误 onerror 抓不到 ← 最常见的坑

3. 资源加载错误 —— img / css / script 加载失败
   window.onerror 完全抓不到!
   必须用 addEventListener('error', handler, true) 捕获阶段

第 2 类的坑最容易漏

// window.onerror / onunhandledrejection 抓不到
fetch('/api/user')
    .then(res => res.json())
    .then(data => data.user.id);   // ✗ 这里报错,监控完全无感知

// 因为:Promise 内部有隐式 try-catch,
// 错误被转为 rejected Promise,不会冒泡到全局

必须显式处理:

// 方案 A:try-catch 包住(能拿到堆栈)
fetch('/api/user')
    .then(res => res.json())
    .then(data => data.user.id)
    .catch(err => {
        // 这里的 err.stack 是完整的
        report(err);
    });

// 方案 B:全局监听 unhandledrejection
window.addEventListener('unhandledrejection', e => {
    report(e.reason);   // e.reason 就是错误对象
    e.preventDefault(); // 阻止默认的 console 输出
});

// 方案 C:全局拦截(适合 axios 这类库)
window.addEventListener('unhandledrejection', e => {
    const reason = e.reason;
    // axios 的错误里 response.data 才是真正的后端错误
    const msg = reason?.response?.data?.message || reason?.message;
    report({ error: msg, stack: reason?.stack });
});

第 3 类要靠捕获阶段

// 必须加第三个参数 true(捕获阶段)
window.addEventListener('error', (e) => {
    // 区分:资源加载错误 vs JS 执行错误
    if (e.target !== window && e.target instanceof HTMLElement) {
        const url = e.target.src || e.target.href;
        report({
            type: 'resource',
            tag: e.target.tagName,
            url,
            // 顺便:给 img 加 error 埋点可以拿到更细的信息
        });
        return;
    }
    // JS 执行错误走 window.onerror
}, true);

一个可用的最小实现

不引入任何 SDK,纯原生也能覆盖 80% 场景:

// error-monitor.js —— 生产环境接入
(function () {
    const ENDPOINT = '/api/frontend-errors';
    const APP_VERSION = window.__APP_VERSION__ || 'unknown';
    const IGNORE = [
        /Script error\./i,        // 跨域脚本拿不到堆栈,无信息量
        /ResizeObserver loop/i,   // 浏览器已知噪声
        /^Script error\.?$/i,
    ];

    function shouldIgnore(msg) {
        if (!msg) return true;
        return IGNORE.some(re => re.test(msg));
    }

    function report(payload) {
        // 用 sendBeacon 保证页面关闭时也能发出去
        const body = JSON.stringify({
            ...payload,
            version: APP_VERSION,
            url: location.href,
            userAgent: navigator.userAgent,
            ts: Date.now(),
            // 用户上下文,排查时非常有用
            userId: window.__USER_ID__ || null,
            traceId: window.__TRACE_ID__ || null,
        });

        if (navigator.sendBeacon) {
            navigator.sendBeacon(ENDPOINT, body);
        } else {
            fetch(ENDPOINT, { method: 'POST', body, keepalive: true });
        }
    }

    // 1. 同步 + 异步错误
    window.addEventListener('error', (e) => {
        // 资源加载错误
        if (e.target !== window && e.target instanceof HTMLElement) {
            const t = e.target;
            report({
                type: 'RESOURCE_LOAD_ERROR',
                message: `资源加载失败: <${t.tagName.toLowerCase()}> ${t.src || t.href}`,
                target: t.tagName,
                src: t.src || t.href,
            });
            return;
        }

        const err = e.error;
        const message = err?.message || e.message || '';
        if (shouldIgnore(message)) return;

        report({
            type: e.type === 'error' ? 'JS_ERROR' : 'UNKNOWN',
            message,
            stack: err?.stack || null,
            line: e.lineno,
            col: e.colno,
            source: e.filename,
        });
    }, true);

    // 2. Promise 未捕获
    window.addEventListener('unhandledrejection', (e) => {
        const reason = e.reason;
        // axios 错误:真正有用的信息在 response.data
        const message = reason?.response?.data?.message
            || reason?.message
            || String(reason);
        if (shouldIgnore(message)) return;

        report({
            type: 'UNHANDLED_REJECTION',
            message,
            stack: reason?.stack || null,
            // axios 的状态码很关键
            status: reason?.response?.status,
            // 后端返回的业务错误码
            bizCode: reason?.response?.data?.code,
        });
        e.preventDefault();
    });

    // 3. 全局兜底:连 handler 都挂了也能记录
    window.addEventListener('error', function fatal(e) {
        report({ type: 'FATAL', message: 'monitor itself crashed' });
        // 移除自身,避免无限递归
        window.removeEventListener('error', fatal);
    });
})();

SourceMap:让堆栈可读

线上代码经过压缩后,堆栈长这样:

at t (app.min.js:1:284519)

这行信息在排查时毫无价值。 必须用 SourceMap 还原。

生产环境要不要上传 SourceMap

要,但不要部署到公开可访问的位置。

两种方案:

方案做法优点缺点
A传到 Sentry 等平台的私有仓库平台自动还原依赖第三方
B存到自己服务器的受保护目录完全自主要自己写还原逻辑

方案 B 的 nginx 配置关键是禁止外部访问:

server {
    # SourceMap 存放目录,禁止外部访问
    location /sourcemaps/ {
        # 只允许内网和特定 IP
        allow 10.0.0.0/8;
        allow 192.168.1.0/24;
        deny all;
        root /var/www/sourcemaps;
    }

    # 线上 js 末尾要注释掉 map 引用,否则会暴露路径
    location /static/ {
        root /var/www;
        # 确保 .map 文件不可直接访问
        location ~ \.map$ {
            deny all;
        }
    }
}

构建产物里必须去掉引用,否则浏览器会去下载 .map 文件:

// vite.config.js
export default defineConfig({
    build: {
        sourcemap: 'hidden',   // 生成但不添加 //# sourceMappingURL 注释
        // 'inline' 更危险,会把 map 塞进 js 文件,文件体积暴涨
    }
});

hidden 与 true 的区别:

sourcemap: true     → 生成 .map + 在 .js 末尾加注释(会暴露路径)
sourcemap: 'hidden' → 生成 .map,不加注释 ← 生产用这个
sourcemap: 'inline' → map 内容直接嵌进 .js(体积 +50%,且浏览器无法单独取)

服务端还原堆栈

# 用 Python 实现 stacktrace-parser + sourcemap 还原
import json
import requests

class SourceMapResolver:
    def __init__(self, map_base_url, web_host):
        self.map_base_url = map_base_url
        self.web_host = web_host
        self._cache = {}

    def resolve(self, stack, app_version):
        """把 minified 堆栈还原成可读堆栈。"""
        cache_key = app_version
        if cache_key not in self._cache:
            self._cache[cache_key] = self._load_map(app_version)

        smap = self._cache[cache_key]
        mappings = smap['mappings']
        sources = smap['sources']

        resolved = []
        for frame in stack.split('\n'):
            m = FRAME_RE.match(frame.strip())
            if not m:
                continue
            line, col = int(m.group(1)), int(m.group(2))
            # 查 mappings 表找到原始位置
            orig_line, orig_col, src = self._lookup(
                mappings, sources, line, col)
            if orig_line:
                resolved.append(
                    f"    at {m.group(3)} ({src}:{orig_line}:{orig_col})")
            else:
                resolved.append(f"    at {m.group(3)} (app.min.js:{line}:{col})")

        return '\n'.join(resolved)

    def _load_map(self, version):
        """下载并缓存 map 文件。"""
        url = f"{self.map_base_url}/app.min.js.map?v={version}"
        r = requests.get(url, timeout=10)
        r.raise_for_status()
        return r.json()

降噪:不然你会被淹没

真实项目里,原始错误一天能上万条,大部分是同一个问题。不做归一化,你根本看不过来。

按 fingerprint 聚合

import hashlib
import re

def fingerprint(error):
    """生成错误指纹:同一个 bug 应该得到同一个指纹。"""
    # 1. 消息里的数字替换掉(id=123 和 id=456 是同一个 bug)
    msg = re.sub(r'\d+', 'N', error['message'])
    # 2. 只取堆栈前三帧(后面的往往是业务调用链,不稳定)
    frames = (error.get('stack') or '').split('\n')[:3]
    frames = [re.sub(r'\?.*', '?', f) for f in frames]

    raw = f"{error['type']}|{msg}|{'|'.join(frames)}"
    return hashlib.md5(raw.encode()).hexdigest()[:16]

效果:

改造前:57 条独立错误
改造后:3 个 issue
  - "Cannot read properties of null" × 41
  - "Network request failed" × 12
  - "ChunkLoadError" × 4

该忽略的噪声

NOISE_PATTERNS = [
    r'Script error\.',                    # 跨域脚本,堆栈被浏览器屏蔽
    r'ResizeObserver loop',               # 浏览器已知问题
    r'Non-Error promise rejection',       # 抛了非 Error 对象
    r'NetworkError when attempting',      # 用户切网/断网
    r'Loading chunk \d+ failed',          # 发布期间的资源失效,可接受
    r'Failed to fetch dynamically imported',  # 同上
]

# 发布窗口期的 chunk 加载失败单独处理:
# 这类错误在发版后 5 分钟内属正常,不告警
def is_ignorable(error):
    msg = error.get('message', '')
    if any(re.search(p, msg) for p in NOISE_PATTERNS):
        # chunk 错误按时间窗口豁免
        if 'chunk' in msg.lower():
            age = time.time() - error['ts'] / 1000
            return age < 300      # 5 分钟内不报
        return True
    return False

ChunkLoadError 值得单独说:每次发版后,用户打开的旧页面会去拉已经不存在的新 chunk,产生大量 404。这不是 bug,5 分钟内豁免即可。

采样

def should_sample(error, rate=1.0):
    """高频错误降采样,低频错误全量上报。"""
    # 每天出现超过 1000 次的错误,按比例采样
    daily_count = get_daily_count(error['fingerprint'])
    if daily_count > 1000:
        return hash(error['id']) % int(1 / rate) == 0
    return True

加用户上下文

没有上下文的错误等于没有错误。 至少带上这些:

report({
    message,
    stack,
    // 用户维度
    userId: window.__USER_ID__,
    // 页面维度
    url: location.href,
    referrer: document.referrer,
    // 链路维度:和后端日志串起来的关键
    traceId: window.__TRACE_ID__,
    // 状态维度
    userAgent: navigator.userAgent,
    screen: `${screen.width}x${screen.height}`,
    networkType: getNetworkType(),   // 4g/3g/offline
    // 版本维度:区分是不是发版引入的
    version: window.__APP_VERSION__,
});

traceId 尤其重要。前端错误 + 后端同一次请求的日志,能定位到具体是哪个接口返回了异常数据。

自查清单

  • 是否监听了 unhandledrejection?(只监听 error 会漏掉 Promise 错误)
  • 资源加载错误是否用了捕获阶段监听(第三个参数 true)?
  • 是否用 sendBeacon 上报?(页面关闭时普通请求会被中断)
  • 生产环境 SourceMap 是否生成但不暴露?(用 sourcemap: 'hidden')
  • 是否做了 fingerprint 归一化?
  • 是否过滤了 Script error. / ResizeObserver loop / chunk 加载失败?
  • 错误里是否带了 version 和 traceId?
  • 告警是否接到了值班群?(监控不告警等于没做)

小结

  • 三类错误三种抓法,最容易漏的是 Promise 内的错误
  • SourceMap 用 'hidden',生成但不暴露
  • 降噪比采集更重要 —— 不做 fingerprint 归一化,监控平台就是个噪音堆
  • 上下文(version / traceId / userId)决定排查效率

下一篇写分库分表,那是从单体到分布式最容易踩坑的一次改造。