0
0

More than 1 year has passed since last update.

【Sentry】Reactプロジェクトで本番環境のみエラー監視を行う

Last updated at Posted at 2021-10-27

はじめに

作成したプロジェクトでフロントエンド側のエラー監視にSentryを導入したのでメモを残します。

実装

大体は公式Docs通りなのですが、ステージング環境のエラーも検知してしまうのが煩わしかったので、if (process.env.NODE_ENV === 'production')で本番環境のみSentry.init()を行うようにしました。

Sentry.setUser()には、エラーが起こったユーザのid username emailが入ってくるようにしました。

SPA全体のエラーを検知するように、<Router>以下で<Sentry.ErrorBoundary>をラッピングするようにしました。
エラーを検知した際に表示される画面として<Fallback />というコンポーネントを作成し、エラー内容が表示されるようにしました。

App.tsx
import * as Sentry from '@sentry/react'
import { Integrations } from '@sentry/tracing'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'

// 本番環境のみエラーを送信する
if (process.env.NODE_ENV === 'production') {
  Sentry.init({
    dsn: SENTRY_PUBLIC_DSN,
    integrations: [new Integrations.BrowserTracing()],
    tracesSampleRate: 1.0,
    environment: process.env.NODE_ENV,
  })
}

const Fallback = ({ error }: { error: Error }) => (
  <div className='container' style={{ fontSize: 18, marginTop: 50, marginBottom: 500 }}>
    {error.toString()}
  </div>
)

const AppRouter = () => {
  const { data, loading } = useInputQuery()

  if (loading || !data) return <ContentLoader />

  Sentry.setUser({
    id: data.u_uid,
    username: data.u_name ?? '',
    email: data.u_mail,
  })

  return (
    <Router>
      <Sentry.ErrorBoundary fallback={({ error }) => <Fallback error={error} />}>
        <Switch>
          <Route path='/1'>
            <ComponentOne />
          </Route>
          <Route path='/2'>
            <ComponentTwo />
          </Route>
          <Route>
            <NotFound />
          </Route>
        </Switch>
      </Sentry.ErrorBoundary>
    </Router>
  )
}

if (document.getElementById('app')) {
  ReactDOM.render(
        <AppRouter />,
    document.getElementById('app')
  )
}

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0