vue实现bug监控
Vue 实现 Bug 监控的方法
使用 Sentry 进行错误监控
Sentry 是一个开源的错误跟踪工具,支持 Vue 项目。安装 @sentry/vue 和 @sentry/tracing 包,在 Vue 应用的入口文件(如 main.js)中初始化 Sentry:
import * as Sentry from "@sentry/vue";
import { Integrations } from "@sentry/tracing";
Sentry.init({
Vue: app,
dsn: "YOUR_DSN_HERE",
integrations: [new Integrations.BrowserTracing()],
tracesSampleRate: 1.0,
});
集成 Vue 错误处理钩子
Vue 提供了全局错误处理钩子 errorHandler,可以捕获组件渲染和事件处理中的错误。在 main.js 中配置:
app.config.errorHandler = (err, vm, info) => {
console.error("Vue Error:", err, info);
// 发送错误到监控服务(如 Sentry)
Sentry.captureException(err, { extra: { info } });
};
监听全局未捕获的异常
通过 window.onerror 捕获未被 Vue 错误处理钩子捕获的异常:
window.onerror = function (message, source, lineno, colno, error) {
console.error("Global Error:", error);
Sentry.captureException(error);
};
监控 Promise 异常
监听未处理的 Promise 异常(如异步请求失败):

window.addEventListener("unhandledrejection", (event) => {
console.error("Unhandled Promise:", event.reason);
Sentry.captureException(event.reason);
});
自定义错误上报
对于特定业务逻辑错误,可以手动上报:
try {
// 业务代码
} catch (err) {
Sentry.captureException(err);
}
集成性能监控
Sentry 的 BrowserTracing 可以监控页面加载性能和路由切换耗时:

integrations: [
new Integrations.BrowserTracing({
routingInstrumentation: Sentry.vueRouterInstrumentation(router),
}),
],
本地开发环境过滤
避免在开发环境下上报错误:
Sentry.init({
dsn: "YOUR_DSN_HERE",
environment: process.env.NODE_ENV,
beforeSend(event) {
if (process.env.NODE_ENV === "development") {
return null; // 阻止开发环境上报
}
return event;
},
});
用户反馈关联
收集用户反馈并与错误关联:
Sentry.showReportDialog({
eventId: "错误事件ID",
});
注意事项
- 确保 DSN 配置正确,且项目有对应的 Sentry 权限。
- 敏感信息需通过
beforeSend钩子过滤。 - 生产环境建议设置合理的
tracesSampleRate(如 0.1)。






