我在我的 CRA 反应应用程序中使用哨兵浏览器。我创建了一个错误边界组件,并使用它来捕获错误。
到目前为止一切顺利,我发现错误并成功将其记录到哨兵。
当我想传递用户信息或设置标签时,问题就来了;这些信息不会被传递,除非我在我的索引文件中设置它(但这样我就无权访问商店,因此无权访问当前用户信息)。
那么,我应该在哪里调用 Sentry.configureScope() 来设置这些信息?
编辑: 我意识到 sentry.configureScope() 实际上在我的记录器函数中工作正常。问题是我试图用 ErrorBoundary 包装 App,除非错误在启动时已经存在,否则它不会被解决。
现在,如果我想保持基本粒度,如何避免将每个组件都包装在 ErrorBoundary 中?
我的代码如下:
指数:
Sentry.init({
dsn: "https://xxxxx.yyyyyyyyy",
environment: process.env.NODE_ENV,
release: '0.1.0'
})
// HERE IT WOULD WORK --------- BUT I HAVE NO STORE ACCESS
/* Sentry.configureScope(scope => {
scope.setExtra('battery', 0.7);
scope.setTag('user_access', 'admin');
scope.setUser({ id: '555' });
}); */
ReactDOM.render(
<Provider store={store}>
<LocalizeProvider store={store}>
<PersistGate loading={<Spinner />} persistor={persistor}>
<ErrorBoundary>
<App />
</ErrorBoundary>
</PersistGate>
</LocalizeProvider>
</Provider>,
document.getElementById('root'));
错误边界.JS
import * as React from 'react'
import * as Sentry from '@sentry/browser';
function logError(error, extraContext = {}) {
Sentry.configureScope(scope => {
scope.setExtra('battery', 0.7);
scope.setTag('user_mode', 'admin');
scope.setUser({ 'id': '4711' });
if(extraContext.extra) {
Object.keys(extraContext.extra).forEach(key => {
scope.setExtra(key, extraContext.extra[key])
})
}
Sentry.captureException(error)
})
}
export default class ErrorBoundary extends React.Component {
state = { error: null }
static getDerivedStateFromError(error) {
return {
error: {
timestamp: new Date().toJSON(),
message: error.message,
}
}
}
componentDidCatch(error, info) {
logError(error, { extra: { ...info } })
}
render() {
const { error } = this.state
if (error != null) {
return <div className="container-fluid">
<h2>An error has occurred</h2>
<div><strong>Message</strong>: {error.message}</div>
<div><strong>Timestamp</strong>: {error.timestamp}</div>
</div>
}
return this.props.children
}
}