最近公司所有的项目都要加上sentry,用来监测项目出错,这里记录一下怎么使用
利用class定义的类组件中使用
1.npm install (yarn add) @sentry/browser
2.在index.js中引入Sentry
// index.js
import * as Sentry from '@sentry/browser';
Sentry.init({ dsn: '这里放申请sentry的时候给你的地址,如http://hash@sentry.io/123' });
3.在组件中
componentDidCatch(error, errorInfo) {
Sentry.withScope((scope) => {
scope.setExtras(errorInfo);
Sentry.captureException(error);
});
}
具体的可以看sentry和react的文档
使用react的hooks定义的函数组件
1.npm install (yarn add) @sentry/browser
2.在index.js中引入Sentry
// index.js
import * as Sentry from '@sentry/browser';
Sentry.init({ dsn: '这里放申请sentry的时候给你的地址,如http://hash@sentry.io/123' });
3.在app.jsx中(全局的方式,这样就不用每一个方法中都写一次了)
import * as Sentry from '@sentry/browser';
const onError = e => {
Sentry.withScope(scope => {
scope.setExtras({ componentStack: e.message });
// 因为我用的是tsx,对类型要求的比较严格,所以才会写成对象的方式传参,componentStack是componentDidcatch的error参数的key
Sentry.captureException(e.error);
});
};
// 必须要用addEventListener,并且第三个参数为true,不然错误无法冒泡到app.jsx中
window.addEventListener('error', onError, true);
网友评论