下面,我们来系统的梳理关于 错误追踪(Sentry 集成) 的基本知识点:
一、Sentry 核心概念
1.1 Sentry 是什么
Sentry 是一个开源的实时错误追踪系统,帮助开发者监控和修复应用程序中的异常。它提供:
- 实时错误警报
- 详细的错误上下文信息
- 错误发生前后的用户操作追踪
- 错误分组和优先级排序
- 发布管理和问题解决跟踪
1.2 错误监控的核心价值
价值点 | 说明 | 业务影响 |
---|
减少用户流失 | 及时发现并修复影响用户体验的错误 | 提升用户留存率 15-30% |
加速问题定位 | 完整上下文信息减少调试时间 | 平均修复时间减少 50-70% |
提升开发效率 | 自动错误分组和优先级排序 | 开发资源聚焦关键问题 |
预防重复错误 | 错误趋势分析和根本原因定位 | 减少同类错误发生率 40-60% |
量化质量指标 | 错误率、影响用户数等指标 | 数据驱动的质量改进 |
1.3 Vue 错误类型分类
二、Sentry 集成步骤
2.1 创建 Sentry 项目
- 访问 sentry.io 注册账户
- 创建新项目 → 选择 Vue 模板
- 获取 DSN(数据源名称):
https://example@sentry.io/12345
2.2 安装依赖
npm install @sentry/vue @sentry/tracing
yarn add @sentry/vue @sentry/tracing
2.3 基础集成配置
import { createApp } from 'vue'
import * as Sentry from '@sentry/vue'
import { Integrations } from '@sentry/tracing'const app = createApp(App)Sentry.init({app,dsn: 'https://example@sentry.io/12345',integrations: [new Integrations.BrowserTracing({routingInstrumentation: Sentry.vueRouterInstrumentation(router),tracingOrigins: ['localhost', 'yourdomain.com'],}),],tracesSampleRate: 0.2,environment: process.env.NODE_ENV,release: 'your-project@1.0.0',
})app.use(router).mount('#app')
2.4 环境变量配置
# .env.production
VUE_APP_SENTRY_DSN=https://example@sentry.io/12345
VUE_APP_RELEASE_VERSION=1.0.0
Sentry.init({dsn: process.env.VUE_APP_SENTRY_DSN,release: process.env.VUE_APP_RELEASE_VERSION,
})
三、高级错误捕获策略
3.1 Vue 错误边界处理
<template><div><sentry-error-boundary :fallback="ErrorComponent"><component-that-may-error /></sentry-error-boundary></div>
</template><script>
import { ErrorBoundary } from '@sentry/vue'export default {components: {'sentry-error-boundary': ErrorBoundary,},data() {return {ErrorComponent: () => import('@/components/ErrorFallback')}}
}
</script>
3.2 全局错误处理器
app.config.errorHandler = (error, vm, info) => {Sentry.captureException(error, {extra: {component: vm.$options.name,props: vm.$props,lifecycleHook: info}})showErrorToast('发生错误,已自动报告')
}
3.3 路由错误捕获
router.onError((error) => {Sentry.captureException(error, {tags: {route: router.currentRoute.value.path}})
})
3.4 异步错误捕获
const safeAsync = (fn) => {return async (...args) => {try {return await fn(...args)} catch (error) {Sentry.captureException(error)throw error}}
}
const fetchData = safeAsync(async () => {const response = await axios.get('/api/data')return response.data
})
四、上下文增强与用户反馈
4.1 自定义上下文信息
Sentry.setUser({id: '12345',email: 'user@example.com',username: 'example_user'
})
Sentry.setTag('page', 'checkout')
Sentry.setExtra('shopping_cart', {items: 3,total: 99.99
})
4.2 用户反馈集成
import * as Sentry from '@sentry/vue'
import { Feedback } from '@sentry-internal/feedback'
const feedback = new Feedback({colorScheme: 'system',buttonLabel: '报告问题',submitButtonLabel: '发送反馈',formTitle: '您遇到了什么问题?',successMessageText: '感谢您的反馈!',
})
feedback.attachTo(Sentry)
4.3 性能监控集成
Sentry.init({integrations: [new Integrations.BrowserTracing({routingInstrumentation: Sentry.vueRouterInstrumentation(router),tracingOrigins: ['localhost', /^\//],}),],tracesSampleRate: 0.2, tracePropagationTargets: ['localhost', /^https:\/\/api\.yourdomain\.com/],
})
五、Source Maps 配置
5.1 为什么需要 Source Maps
- 生产环境代码经过压缩混淆
- Sentry 需要原始代码定位错误
- 提供精确的错误堆栈信息
- 显示原始源代码而非编译后代码
5.2 Webpack 配置示例
const { defineConfig } = require('@vue/cli-service')
const SentryWebpackPlugin = require('@sentry/webpack-plugin')module.exports = defineConfig({configureWebpack: {devtool: 'source-map',plugins: [new SentryWebpackPlugin({authToken: process.env.SENTRY_AUTH_TOKEN,org: 'your-org',project: 'your-project',release: process.env.VUE_APP_RELEASE_VERSION,include: './dist',ignore: ['node_modules', 'webpack.config.js'],urlPrefix: '~/',setCommits: {auto: true}})]}
})
5.3 Vite 配置示例
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import sentryVitePlugin from '@sentry/vite-plugin'export default defineConfig({build: {sourcemap: true},plugins: [vue(),sentryVitePlugin({authToken: process.env.SENTRY_AUTH_TOKEN,org: 'your-org',project: 'your-project',release: process.env.VUE_APP_RELEASE_VERSION,sourcemaps: {assets: './dist/**'}})]
})
六、生产环境最佳实践
6.1 错误过滤策略
Sentry.init({beforeSend(event) {if (event.exception.values[0].value.includes('ResizeObserver')) {return null}const statusCode = event.extra?.response?.statusif (statusCode === 401 || statusCode === 403) {return null}return event},ignoreErrors: [/Network Error/,/Request failed with status code 503/,'IgnoredError']
})
6.2 采样率控制
Sentry.init({tracesSampler: samplingContext => {if (samplingContext.location.path.includes('/health')) {return 0}if (samplingContext.transactionContext.name === 'checkout') {return 1.0}return 0.2}
})
6.3 敏感数据过滤
Sentry.init({sendDefaultPii: false, beforeSend(event) {event.request.headers['Authorization'] = '[Filtered]'if (event.extra?.userData) {event.extra.userData.password = '[Filtered]'event.extra.userData.creditCard = '[Filtered]'}return event}
})
七、CI/CD 集成
7.1 GitHub Actions 集成示例
name: Release and Upload Source Mapson:release:types: [published]jobs:build:runs-on: ubuntu-lateststeps:- name: Checkout codeuses: actions/checkout@v3- name: Setup Node.jsuses: actions/setup-node@v3with:node-version: 18- name: Install dependenciesrun: npm ci- name: Build production assetsrun: npm run buildenv:VUE_APP_RELEASE_VERSION: ${{ github.ref_name }}- name: Upload source maps to Sentryuses: getsentry/action-release@v1env:SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}SENTRY_ORG: your-orgSENTRY_PROJECT: your-projectwith:environment: productionsourcemaps: ./distrelease: ${{ github.ref_name }}- name: Deploy to productionrun: npm run deploy
7.2 发布管理策略
sentry-cli releases new your-project@1.2.3
sentry-cli releases set-commits your-project@1.2.3 --auto
sentry-cli releases finalize your-project@1.2.3
sentry-cli releases deploys your-project@1.2.3 new -e production
八、错误分析与处理流程
8.1 Sentry 控制台功能
功能 | 说明 | 使用场景 |
---|
问题列表 | 错误分组展示 | 快速定位高频错误 |
问题详情 | 完整错误上下文 | 分析错误原因 |
用户反馈 | 关联的用户反馈 | 理解用户影响 |
面包屑 | 用户操作路径 | 重现错误流程 |
性能分析 | 关联性能指标 | 定位性能瓶颈 |
发布跟踪 | 错误版本分布 | 验证修复效果 |
8.2 错误处理工作流
graph LRA[收到错误警报] --> B[分析错误详情]B --> C{是否已知问题?}C -->|是| D[关联已有Issue]C -->|否| E[创建新Issue]E --> F[分配负责人]F --> G[修复并测试]G --> H[部署新版本]H --> I[验证修复效果]I --> J[关闭Issue]
8.3 错误解决最佳实践
- 优先级排序:
- 根本原因分析:
- 使用面包屑追踪用户操作路径
- 分析环境、设备和浏览器分布
- 修复验证:
- 使用 Sentry 的 Release 比较功能
- 监控修复后的错误率下降趋势
- 知识沉淀:
- 记录解决方案到内部 Wiki
- 添加预防措施到代码审查清单
九、实践方案
9.1 错误监控架构设计
+-----------------+| Vue 应用 |+--------+--------+|+--------+--------+| Sentry SDK |+--------+--------+|+---------------+---------------+| |
+-------+-------+ +---------+---------+
| Sentry 服务 | | 内部日志系统 |
+---------------+ +-------------------+|
+-------+-------+
| 报警系统 | → Slack/邮件/钉钉
+---------------+
9.2 监控指标与告警
指标 | 阈值 | 告警渠道 |
---|
错误率 | > 1% | 紧急电话 |
关键事务错误 | > 0 | 即时消息 |
影响用户数 | > 100 | 邮件+消息 |
新错误出现 | 任何 | 每日报告 |
回归错误 | 任何 | 即时消息 |
9.3 多环境策略
const getSentryConfig = () => {const env = process.env.NODE_ENVconst configs = {development: {dsn: null, tracesSampleRate: 0},staging: {dsn: 'STAGING_DSN',tracesSampleRate: 1.0 },production: {dsn: 'PRODUCTION_DSN',tracesSampleRate: 0.2}}return configs[env] || configs.development
}Sentry.init({...getSentryConfig(),integrations: []
})
十、常见问题与解决方案
10.1 集成问题排查
问题 | 可能原因 | 解决方案 |
---|
无错误上报 | DSN 配置错误 | 检查项目DSN和权限 |
Source Maps 失效 | 路径不匹配 | 检查 urlPrefix 配置 |
缺少面包屑 | 集成未启用 | 添加 BrowserTracing |
用户信息缺失 | 未调用 setUser | 在认证后设置用户 |
性能数据缺失 | 采样率过低 | 调整 tracesSampleRate |
10.2 错误处理最佳实践
- 避免全局捕获后吞没错误:
window.onerror = () => true
Vue.config.errorHandler = (err) => {Sentry.captureException(err)throw err
}
- 合理设置错误采样率:
beforeSend(event) {const isCritical = event.tags?.critical === 'true'return isCritical ? event : null
}
- 定期审查忽略规则:
ignoreErrors: [
]
十一、 总结
Vue 应用集成 Sentry 的核心价值:
关键实践要点
- 正确集成:配置 SDK 和 Source Maps
- 全面捕获:覆盖全局错误、异步错误、路由错误
- 丰富上下文:添加用户信息、面包屑、自定义标签
- 智能过滤:忽略无关错误,聚焦关键问题
- 闭环管理:从警报到修复的完整工作流
- 持续优化:基于数据驱动质量改进