Errori di seguimentu in una app React cù Sentry

Errori di seguimentu in una app React cù Sentry

Oghje vi spiegheraghju u seguimentu di l'errore in tempu reale in una app React. L'applicazione frontend ùn hè micca tipicamente usata per u seguimentu di bug. Certi cumpagnii spessu mettenu da parte u seguimentu di bug, tornanu à ellu dopu a documentazione, testi, etc. Tuttavia, se pudete cambià u vostru pruduttu per u megliu, fate solu!

1. Perchè avete bisognu di Sentry ?

Supponu chì site interessatu à u seguimentu di bug durante a produzzione.

Pensate chì questu ùn hè micca abbastanza?

Va bè, fighjemu i dettagli.

Principali motivi per aduprà Sentry per i sviluppatori:

  • Permette di sbarazzarsi di risichi quandu si sparghje u codice cù errori
  • Aiutu QA in teste di codice
  • Ricevi notifiche veloci di prublemi
  • Capacità di risolve rapidamente errori
  • Ottene una visualizazione conveniente di l'errori in u pannellu di amministrazione
  • Ordine l'errori per segmentu d'utilizatore / navigatore

Motivi principali per u prughjettu CEO / Lead

  • Risparmiate soldi (Sentry pò esse installatu nantu à i vostri servitori)
  • Ottene feedback di l'utilizatori
  • Capisce ciò chì hè sbagliatu cù u vostru prughjettu in tempu reale
  • Capisce u numeru di prublemi chì e persone anu cù a vostra app
  • Aiutate à truvà lochi induve i vostri sviluppatori anu fattu un sbagliu

Pensu chì i sviluppatori anu da esse interessatu in questu articulu in u primu locu. Tù dinù ponu aduprà sta lista di mutivi di cunvince u vostru capu à integrà Sentry.

Attenti cù l'ultimu articulu nantu à a lista di l'affari.

Sò digià interessatu ?

Errori di seguimentu in una app React cù Sentry

Cosa hè Sentry?

Sentry hè una applicazione di tracciamentu di bug open source chì aiuta i sviluppatori à seguità è risolve i crash in tempu reale. Ùn vi scurdate chì l'app permette ancu di aumentà l'efficienza è migliurà l'esperienza di l'utilizatori. Sentry supporta JavaScript, Node, Python, PHP, Ruby, Java è altre lingue di prugrammazione.

Errori di seguimentu in una app React cù Sentry

2. Login è creà un prughjettu

  • Aprite u vostru contu Sentry. Pudete bisognu di firmà. (Per piacè nutate chì Sentry pò esse installatu nantu à i vostri servitori)
  • U prossimu passu hè di creà un prughjettu
  • Sceglite a vostra lingua da a lista. (Andemu à sceglie React. Cliccate "Create Project")

Errori di seguimentu in una app React cù Sentry

Configurate a vostra applicazione. Pudete vede un esempiu basicu di cumu integrà Sentry in un containeru quì sottu:

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 hà un assistente utile per aiutà à capisce ciò chì duvete fà dopu. Pudete seguità i passi sottu. Vogliu vede cumu creà u vostru primu gestore di errore. Grande, avemu creatu un prughjettu! Andemu à u passu prossimu

3. Integrating React è Sentry

Duvete installà u pacchettu npm in u vostru prughjettu.

npm i @sentry/browser

Inizializza Sentry in u vostru containeru:

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

U DSN hè situatu in Prughjetti -> Settings -> Client Keys. Pudete truvà e chjave di u cliente in a barra di ricerca.

Errori di seguimentu in una app React cù Sentry

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

4. Tracking u primu errore

Per esempiu, aghju utilizatu una applicazione musicale simplice cù l'API Deezer. Pudete vede ccà. Avemu bisognu di creà un bug. Una manera hè di accede à a pruprietà "indefinita".

Avemu bisognu di creà un buttone chì chjama cunsola.log с user.email. Dopu à sta azione, duvemu riceve un missaghju d'errore: Uncaught TypeError (ùn pò micca leghje a pruprietà da undefined email) a causa di l'absenza di un oggettu d'utilizatore. Pudete ancu aduprà eccezzioni javascript.

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

Tuttu u containeru s'assumiglia cusì:

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

Dopu avè integratu stu buttone, duvete pruvà in u navigatore.

Errori di seguimentu in una app React cù Sentry

Avemu u nostru primu errore

Errori di seguimentu in una app React cù Sentry

uuuuu !

Errori di seguimentu in una app React cù Sentry

Se cliccate nantu à l'errore di l'intestazione, vi vede a traccia di stack.

Errori di seguimentu in una app React cù Sentry

I missaghji vedenu male. Di sicuru, avemu vistu missaghji errore senza capisce induve stu codice hè. Per automaticamente, si tratta di a mappa fonte in ReactJS perchè ùn sò micca cunfigurati.

Mi piacerebbe ancu furnisce struzzioni per a stallazione di a mappa fonte, ma chì renderebbe stu post assai più longu di ciò chì vulia.

Pudete studià stu tema ccà. Sè site interessatu in questu articulu, Dmitri Nozhenko publicà a seconda parte nantu à l'integrazione di a mappa fonte. Allora cliccate più Mi piace è abbonate Dmitri Nozhenkoper ùn mancà a seconda parte.

5. Usu U centru cun endpoint API

OK. Avemu coperto l'eccezzioni javascript in i paragrafi precedenti. Tuttavia, chì facemu cù l'errori XHR?

Sentry hà ancu una gestione d'errore persunalizata. L'aghju utilizatu per u seguimentu di bug api.

Sentry.captureException(err)

Pudete persunalizà u nome di u bug, u livellu, aghjunghje dati, dati unichi di l'utilizatori via a vostra app, email, etc.

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

Vogliu aduprà una funzione generica per l'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);
};

Impurtà sta funzione in l'api call.

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

Fighjemu i metudi:

  • setLevel permette di inserisce un errore di livellu in u dashboard di a sentinella. Havi proprietà - "fatale", "errore", "avvertimentu", "log", "info, debug", "critical").
  • setUser aiuta à salvà qualsiasi dati d'utilizatori (id, indirizzu email, pianu di pagamentu, etc.).
  • setExtra permette di stabilisce qualsiasi dati chì avete bisognu, per esempiu, una tenda.

Se vulete feedback di l'utilizatori nantu à un bug, duvete aduprà a funzione showReportDialog.

Sentry.showReportDialog();

Cunsigliu:

Oghje avemu descrittu unu di i modi per integrà Sentry in una applicazione React.

→ Telegram chat da U centru

Source: www.habr.com

Add a comment