react 中引入sentry

安装

# 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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值