天天看點

React內建Sentry

要将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;
        }
    }
}