简单尝试

  1. 进入sentry官网注册账户: https://sentry.io
  2. 安装依赖: npm install @sentry/react
  3. 在入口文件配置sentry
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import * as Sentry from '@sentry/react';
import './index.css';
import App from './App.tsx';

Sentry.init({
dsn: '你的Sentry DSN地址',
// Setting this option to true will send default PII data to Sentry.
// For example, automatic IP address collection on events
sendDefaultPii: true,
});

createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>
);

  1. 捕获自定义异常:
1
2
3
4
5
6
7
8
9
10
11
12
13
function ErrorButton() {
return (
<button
onClick={() => {
throw new Error('This is your first error!');
}}
>
Break the world
</button>
);
}
export default ErrorButton;

引入组件,点击按钮,然后,你就可以在sentry上看到异常了!!!

扩展配置:

  • 上报用户信息:便于定位特定用户的问题
1
Sentry.setUser({ id: '用户ID', email: '用户邮箱' });
  • 过滤无关错误:忽略不需要监控的异常(如开发环境报错)
1
2
3
4
5
6
7
  Sentry.init({
// ...其他配置
beforeSend(event) {
if (process.env.NODE_ENV === 'development') return null; // 开发环境不上报
return event;
}
});

多端适配要点

  • 小程序(如 Taro/uni-app):安装 @sentry/minimal 轻量包,通过小程序生命周期(如 onLaunch)初始化,需适配小程序的错误监听(如wx.onError)。
  • Vue 项目:替换依赖为 @sentry/vue,在 main.js 中通过 app.use(Sentry, { dsn: 'xxx' }) 集成,自动捕获 Vue 组件生命周期错误。

接入后可自动捕获「JS 运行时错误、接口请求错误、资源加载失败、性能异常」等,在 Sentry 后台查看错误堆栈、发生环境、影响用户数,还能配置告警(邮件 / 钉钉),让问题修复时效缩短