meta-description: 使用Sentry进行前端错误监控完整教程,详解Source Map、性能监控和告警配置。

keywords: Sentry,前端错误监控,Source Map,性能监控,前端告警

# 使用Sentry进行前端错误监控

本文详细介绍如何使用Sentry监控前端错误,包括Source Map配置、性能监控和告警设置。

## 为什么需要前端监控

| 问题 | 传统方式 | Sentry方案 |

|------|----------|------------|

| 用户报错 | 被动等待反馈 | 主动捕获错误 |

| 定位问题 | 无法复现 | 完整错误上下文 |

| 性能优化 | 无数据支撑 | Core Web Vitals数据 |

| 发布验证 | 手动测试 | 自动回归检测 |

## Sentry基础集成

### 在React项目中集成


# 安装依赖
npm install @sentry/react @sentry/tracing

// src/sentry.js
import * as Sentry from "@sentry/react";
import { BrowserTracing } from "@sentry/tracing";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [new BrowserTracing()],
  tracesSampleRate: 1.0,  // 性能采样率
  environment: process.env.NODE_ENV,
  release: "my-app@1.0.0",
});

// 包装React根组件
export const SentryErrorBoundary = Sentry.ErrorBoundary;

### 在Vue 3项目中集成


// main.js
import { createApp } from "vue";
import * as Sentry from "@sentry/vue";

const app = createApp(App);

Sentry.init({
  app,
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    new Sentry.BrowserTracing({
      routingInstrumentation: Sentry.vueRouterInstrumentation(router),
    }),
  ],
  tracesSampleRate: 1.0,
});

## Source Map配置

### 构建时上传Source Map


// vite.config.js
import { defineConfig } from "vite";
import { sentryVitePlugin } from "@sentry/vite-plugin";

export default defineConfig({
  plugins: [
    sentryVitePlugin({
      org: "your-org",
      project: "your-project",
      authToken: process.env.SENTRY_AUTH_TOKEN,
    }),
  ],
  build: {
    sourcemap: true,  // 必须开启
  },
});

### 手动上传Source Map


# 安装Sentry CLI
npm install -g @sentry/cli

# 登录
sentry-cli login

# 上传Source Map
sentry-cli sourcemaps upload \
  --org your-org \
  --project your-project \
  ./dist \
  https://example.com/assets

## 性能监控

### 自动性能监控


// Sentry自动监控:
// - 页面加载性能
// - 路由切换性能
// - Fetch/XHR请求耗时
// - 用户交互延迟

// 自定义性能监控
import * as Sentry from "@sentry/react";

function loadData() {
  return Sentry.startSpan(
    {
      op: "function",
      name: "load_user_data",
    },
    async () => {
      const response = await fetch("/api/user");
      return response.json();
    }
  );
}

### Web Vitals监控


// Sentry自动采集Web Vitals:
// - LCP (Largest Contentful Paint)
// - FID (First Input Delay) → 2026年起被INP取代
// - CLS (Cumulative Layout Shift)

// 在Sentry Dashboard查看Web Vitals分布

## 错误过滤与采样

### 忽略特定错误


Sentry.init({
  dsn: "...",
  beforeSend(event) {
    // 忽略网络错误
    if (event.exception) {
      const error = event.exception.values[0];
      if (error.type === "NetworkError") {
        return null;  // 不上报
      }
    }
    
    // 过滤敏感信息
    if (event.request?.cookies) {
      delete event.request.cookies;
    }
    
    return event;
  },
});

### 错误采样


Sentry.init({
  dsn: "...",
  sampleRate: 1.0,          // 错误上报率(生产可设为0.5)
  tracesSampleRate: 0.5,     // 性能采样率
  
  // 按用户ID抽样(保证同一用户行为连贯)
  tracesSampler(samplingContext) {
    if (samplingContext.user?.id === "vip_user") {
      return 1.0;  // VIP用户全量采样
    }
    return 0.1;  // 普通用户10%采样
  },
});

## 告警配置

### 创建告警规则


Sentry控制台 → Alerts → Create Alert Rule

规则示例1:错误数量阈值
  - Event: Error count
  - Threshold: > 100 errors in 1 hour
  - Action: 发送Slack通知

规则示例2:用户影响面
  - Event: Users affected
  - Threshold: > 50 unique users in 10 minutes
  - Action: 发送邮件 + PagerDuty

### 集成通知渠道


// Slack集成(官方支持)
// Sentry → Settings → Integrations → Slack

// 自定义Webhook
Sentry.init({
  dsn: "...",
  integrations: [
    new Sentry.Integrations.Http({
      breadcrumbs: true,
      tracing: true,
    }),
  ],
});

## 发布管理

### 关联Commit和Release


# 创建Release
sentry-cli releases new my-app@1.0.0

# 关联Commits
sentry-cli releases set-commits my-app@1.0.0 --commit "owner/repo@abc123"

# 完成Release
sentry-cli releases finalize my-app@1.0.0

### 回归检测


Sentry自动对比当前Release与前一Release的错误率:
- 如果新版本错误率显著上升 → 自动标记Regression
- 在Issue详情页查看引入Regression的Commit

## 实战:WordPress前端监控

### 在WordPress主题中集成


// functions.php
function enqueue_sentry() {
    wp_enqueue_script('sentry', 'https://browser.sentry-cdn.com/7.x.x/bundle.tracing.min.js', [], null, true);
    
    wp_add_inline_script('sentry', '
        Sentry.init({
            dsn: "' . esc_js(getenv('SENTRY_DSN')) . '",
            environment: "' . wp_get_environment_type() . '",
            integration: [new Sentry.Integrations.BrowserTracing()],
        });
    ');
}
add_action('wp_enqueue_scripts', 'enqueue_sentry');

## 最佳实践

1. 生产环境务必开启Source Map上传:否则错误信息无法定位到源码

2. 合理设置采样率:高流量站点错误采样率设为0.1~0.5

3. 利用Breadcrumbs还原用户行为:Sentry自动记录用户点击、导航、控制台日志

4. 配置告警抑制:避免非工作时间被频繁唤醒

## 费用参考

| 方案 | 错误事件/月 | 性能事件/月 | 价格 |

|------|-------------|-------------|------|

| 免费版 | 5,000 | 不支持 | $0 |

| Team | 50,000 | 50,000 | $26/月 |

| Business | 无限制 | 无限制 | $80/月 |

前端错误监控能帮助你主动发现并修复问题,显著改善用户体验。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。