要将Sentry与React应用程序一起使用,您需要使用@ sentry / browser(Sentry的浏览器JavaScript SDK)。
@ sentry / browser本身会报告从您的应用程序触发的任何未捕获的异常。
如果您使用的是React 16或更高版本,则错误边界是用于在面临错误时定义应用程序行为的重要工具。确保使用Sentry.captureException将他们捕获的错误发送给Sentry,并且可选地,这也是一个很好的机会来反映用户反馈。
import * as Sentry from '@sentry/browser';
// Sentry.init({
// dsn: "https://<key>@sentry.io/<project>"
// });
// should have been called before using it here
// ideally before even rendering your react app
class ExampleBoundary extends Component {
constructor(props) {
super(props);
this.state = { error: null };
}
componentDidCatch(error, errorInfo) {
this.setState({ error });
Sentry.withScope(scope => {
Object.keys(errorInfo).forEach(key => {
scope.setExtra(key, errorInfo[key]);
});
Sentry.captureException(error);
});
}
render() {
if (this.state.error) {
//render fallback UI
return (
<a onClick={() => Sentry.showReportDialog()}>Report feedback</a>
);
} else {
//when there's not an error, render children untouched
return this.props.children;
}
}
}