安装
# Using yarn$ yarn add @sentry/browser
或
# Using npm$ npm install @sentry/browser
引入sentry
import React from 'react';
import ReactDOM from 'react-dom';
import * as Sentry from '@sentry/browser';
import App from 'src/App';
Sentry.init({dsn: "https://<key>@sentry.io/<project>"});
ReactDOM.render(<App />, document.getElementById('root'));
触发错误验证
return <button onClick={methodDoesNotExist}>Break the world</button>;
Error Boundaries
如果你使用的是react16以上版本, Error Boundaries 在定义你的应用程序出现错误时如何展示很有用. 确保使用Sentry.captureException把他捕捉到的错误发送到sentry。这里也可通过Sentry.showReportDialog收集用户反馈。
注意:开发模式下, React 会 rethrow error boundary中捕获的错误。 这会导致发送两次错误报告到sentry, 但在产品阶段不会出现此问题.i
import React, { Component } from 'react';
import * as Sentry from '@sentry/browser';
class ExampleBoundary extends Component {
constructor(props) {
super(props);
this.state = { eventId: null };
}
static getDerivedStateFromError() {
return { hasError: true };
}
// 捕获错误
componentDidCatch(error, errorInfo) {
Sentry.withScope((scope) => {
scope.setExtras(errorInfo);
const eventId = Sentry.captureException(error);
this.setState({eventId});
});
}
render() {
if (this.state.hasError) {
//收集用户反馈
return (
<button
onClick{() =>
Sentry.showReportDialog({ eventId: this.state.eventId })
}
>
Report feedback
</button>
);
}
//没有错误的时候显示
return this.props.children;
}}
export default ExampleBoundary