使用 Sentry 追蹤 React 應用程式中的錯誤

使用 Sentry 追蹤 React 應用程式中的錯誤

今天我將向您介紹 React 應用程式中的即時錯誤追蹤。 前端應用程式通常不用於錯誤追蹤。 一些公司經常推遲錯誤跟踪,在文件、測試等之後再返回。 但是,如果您可以使您的產品變得更好,那就去做吧!

1. 為什麼需要哨兵?

我假設您對追蹤生產過程中的錯誤感興趣

您認為這還不夠嗎?

好吧,讓我們來看看細節。

開發人員使用 Sentry 的主要原因:

  • 讓您在部署有錯誤的程式碼時避免風險
  • 幫助 QA 進行程式碼測試
  • 接收有關問題的快速通知
  • 快速糾正錯誤的能力
  • 在管理面板中方便地顯示錯誤
  • 依使用者/瀏覽器段對錯誤進行排序

擔任執行長/領導專案的主要原因

  • 省錢(Sentry 可以安裝在您的伺服器上)
  • 獲取用戶回饋
  • 即時了解您的專案出了什麼問題
  • 了解人們在使用您的應用程式時遇到的問題數量
  • 幫助您找到開發人員犯錯的地方

我認為開發人員首先會對這篇文章感興趣。 您也可以使用這一系列理由來說服您的老闆整合 Sentry。

請小心業務清單上的最後一項。

您已經感興趣了嗎?

使用 Sentry 追蹤 React 應用程式中的錯誤

什麼是哨兵?

Sentry 是一款開源錯誤追蹤應用程序,可協助開發人員即時追蹤和修復崩潰。 不要忘記該應用程式可以讓您提高效率並改善用戶體驗。 Sentry 支援 JavaScript、Node、Python、PHP、Ruby、Java 等程式語言。

使用 Sentry 追蹤 React 應用程式中的錯誤

2. 登入並建立項目

  • 打開您的哨兵帳戶。 您可能需要登入。 (請注意,Sentry 可以安裝在您的伺服器上)
  • 下一步是建立一個項目
  • 從清單中選擇您的語言。 (我們將選擇 React。點擊“建立專案”)

使用 Sentry 追蹤 React 應用程式中的錯誤

自訂您的應用程式。 以下是如何將 Sentry 整合到容器中的基本範例:

import * as Sentry from '@sentry/browser';
// Sentry.init({
//  dsn: "<https://[email protected]/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 位於專案 -> 設定 -> 用戶端金鑰中。 您可以在搜尋欄中找到客戶端金鑰。

使用 Sentry 追蹤 React 應用程式中的錯誤

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

4. 追蹤第一個錯誤

例如,我使用了帶有 Deezer API 的簡單音樂應用程式。 你可以看到 這裡。 我們需要創建一個錯誤。 一種方法是存取“未定義”屬性

我們需要創建一個調用的按鈕 控制台日誌 с 使用者信箱。 執行此操作後,我們應該收到一條錯誤訊息: 未捕獲的類型錯誤(無法從未定義的屬性中讀取屬性 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://[email protected]/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);

整合此按鈕後,您應該在瀏覽器中測試它。

使用 Sentry 追蹤 React 應用程式中的錯誤

我們遇到了第一個錯誤

使用 Sentry 追蹤 React 應用程式中的錯誤

呼呼!

使用 Sentry 追蹤 React 應用程式中的錯誤

如果單擊標題錯誤,您將看到堆疊追蹤。

使用 Sentry 追蹤 React 應用程式中的錯誤

這些消息看起來很糟糕。 當然,我們看到過錯誤訊息,但不了解程式碼在哪裡。 預設情況下,我們討論的是 ReactJS 中的來源映射,因為它們沒有配置。

我還想提供有關設定來源映射的說明,但這將使本文比我預期的要長得多。

你可以研究這個主題 這裡。 如果您對這篇文章有興趣, 德米特里·諾任科 將發布有關來源地圖整合的第二部分。 所以,多按讚和訂閱吧 德米特里·諾任科以免錯過第二部分。

5. 用法 哨兵 有終點 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": "[email protected]"})
          .setLevel("Error")
      );
      return Sentry.captureException(err);
    }

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

我想對 catch API 使用通用函數。

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));
      }
    });
};

我們來檢查一下方法:

  • 設定等級 允許您將等級錯誤插入哨兵儀表板。 它具有屬性 -“致命”、“錯誤”、“警告”、“日誌”、“訊息”、“調試”、“嚴重”)。
  • 設定用戶 有助於保存任何使用者資料(ID、電子郵件地址、付款計劃等)。
  • 設定額外 允許您指定您需要的任何數據,例如儲存。

如果您想獲得有關錯誤的使用者回饋,您應該使用 showReportDialog 函數。

Sentry.showReportDialog();

結論:

今天我們描述了一種將 Sentry 整合到 React 應用程式中的方法。

→ 電報聊天 哨兵

來源: www.habr.com

添加評論