使用Sentry跟踪React应用中的错误



今天,我将向您介绍React应用程序中的实时错误跟踪。前端应用程序通常不用于错误跟踪。一些公司经常通过在文档,测试等之后返回错误跟踪来推迟错误跟踪。但是,如果您可以更好地更改产品,那就去做吧!



1.为什么需要哨兵?



我假设您有兴趣在生产期间跟踪错误



您认为这还不够吗?



好的,让我们看看细节。



对开发人员使用Sentry的主要原因:



  • 消除部署错误代码的风险
  • QA协助代码测试
  • 快速获取问题通知
  • 快速修复错误的能力
  • 在管理面板中方便地显示错误
  • 按用户/浏览器细分排序错误


项目首席执行官/负责人的主要原因



  • 省钱(可以在您的服务器上安装Sentry)
  • 获取用户反馈
  • 实时了解您的项目出了什么问题
  • 了解人们在您的应用程序中遇到的问题数量
  • 帮助您找到开发人员犯错的地方


, . , Sentry.



.



?





Sentry?



Sentry – , , . , . Sentry JavaScript, Node, Python, PHP, Ruby, Java .





2.



  • Sentry . , . ( Sentry )
  • . ( React. « »)




. , Sentry , :



import * as Sentry from '@sentry/browser';
// Sentry.init({
//  dsn: "<https://63bbb258ca4346139ee533576e17ac46@sentry.io/1432138>"
// });
// 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;
        }
    }
}


Sentry , , . . , . , !



3. React Sentry



npm .



npm i @sentry/browser


Sentry :



Sentry.init({
 // dsn: #dsnUrl,
});


DSN Projects -> Settings -> Client Keys. .





componentDidCatch(error, errorInfo) {
  Sentry.withScope(scope => {
    Object.keys(errorInfo).forEach(key => {
      scope.setExtra(key, errorInfo[key]);
    });
    Sentry.captureException(error);
 });
}


4.



API Deezer. . . "undefined"



, console.log user.email. : Uncaught TypeError ( email) - . Javascript.



<button type="button" onClick={() => console.log(user.email)}>   
  Test Error button 
</button>


:



import React, { Component } from "react";
import { connect } from "react-redux";
import { Input, List, Skeleton, Avatar } from "antd";
import * as Sentry from "@sentry/browser";
import getList from "../store/actions/getList";

const Search = Input.Search;

const mapState = state => ({
  list: state.root.list,
  loading: state.root.loading
});

const mapDispatch = {
  getList
};

class Container extends Component {
  constructor(props) {
    super(props);

    Sentry.init({
      dsn: "https://fc0edcf6927a4397855797a033f04085@sentry.io/1417586",
    });
  }

  componentDidCatch(error, errorInfo) {
    Sentry.withScope(scope => {
      Object.keys(errorInfo).forEach(key => {
        scope.setExtra(key, errorInfo[key]);
      });
      Sentry.captureException(error);
    });
  }
  render() {
    const { list, loading, getList } = this.props;
    const user = undefined;
    return (
      <div className="App">
        <button
          type="button"
          onClick={() => console.log(user.email)}
        >
          test error1
        </button>
        <div onClick={() => Sentry.showReportDialog()}>Report feedback1</div>
        <h1>Music Finder</h1>
        <br />
        <Search onSearch={value => getList(value)} enterButton />
        {loading && <Skeleton avatar title={false} loading={true} active />}
        {!loading && (
          <List
            itemLayout="horizontal"
            dataSource={list}
            locale={{ emptyText: <div /> }}
            renderItem={item => (
              <List.Item>
                <List.Item.Meta
                  avatar={<Avatar src={item.artist.picture} />}
                  title={item.title}
                  description={item.artist.name}
                />
              </List.Item>
            )}
          />
        )}
      </div>
    );
  }
}

export default connect(
  mapState,
  mapDispatch
)(Container);


.









Whoo-hoo!





, .





. , , , . ReactJS, .



, , .



. , Dmitry Nozhenko source map. , Dmitry Nozhenko, .



5. Sentry API



. javascript . , XHR?



Sentry . api.



Sentry.captureException(err)


, , , , . .



superagent
  .get(`https://deezerdevs-deezer.p.rapidapi.com/search?q=${query}`)
  .set("X-RapidAPI-Key", #id_key)
  .end((err, response) => {
    if (err) {
      Sentry.configureScope(
        scope => scope
          .setUser({"email": "john.doe@example.com"})
          .setLevel("Error")
      );
      return Sentry.captureException(err);
    }

    if (response) {
      return dispatch(setList(response.body.data));
    }
  });


API catch.



import * as Sentry from "@sentry/browser";

export const apiCatch = (error, getState) => {
  const store = getState();
  const storeStringify = JSON.stringify(store);
  const { root: { user: { email } } } = store;

  Sentry.configureScope(
    scope => scope
      .setLevel("Error")
      .setUser({ email })
      .setExtra("store", storeStringify)
  );
    // Sentry.showReportDialog(); - If you want get users feedback on error
  return Sentry.captureException(error);
};


api.



export default query => (dispatch, getState) => {
  superagent
    .get(`https://deezerdevs-deezer.p.rapidapi.com/search?q=${query}`)
    .set("X-RapidAPI-Key", #id_key)
    .end((error, response) => {
      if (error) {
        return apiCatch(error, getState)
      }

      if (response) {
        return dispatch(setList(response.body.data));
      }
    });
};


:



  • setLevel sentry. — ‘fatal’, ‘error’, ‘warning’, ‘log’, ‘info, ‘debug’, ‘critical’).
  • setUser (id, , . .).
  • setExtra , , , .


如果要获得用户对错误的反馈,则应使用showReportDialog函数。



Sentry.showReportDialog();


输出:



今天,我们描述了一种将Sentry集成到React应用程序中的方法。



→通过哨兵进行电报聊天




All Articles