LoginSignup
20
12

More than 3 years have passed since last update.

Vueのエラー監視にSentryを使ってみた

Last updated at Posted at 2019-12-07

フロントエンドのエラーって見落としがちですよね。
ユーザーにエラーのアラートを表示しても連絡がなければ開発者はそのエラーに気づくことができません。
そもそもエラー処理が適切に行えておらず、consoleをみるとエラーだらけなんてもことも。

Sentryでエラーを監視する

Sentryを使えばエラーを見落とすことはなくなるでしょう。発生したエラーをキャッチし、メールやSlackで通知してくれます。

SDKをインストール

今回はVueで使用するので、Browser > Vueを選択します。

スクリーンショット 2019-12-04 23.50.23.png

yarn add @sentry/browser
yarn add @sentry/integrations
main.ts
// sentry
import * as Sentry from '@sentry/browser';
import * as Integrations from '@sentry/integrations';
Sentry.init({
  dsn: 'https://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  integrations: [new Integrations.Vue({Vue, attachProps: true})],
});

エラー発生するコンポーネントを作成

クリックするとエラーを投げるボタンだけのコンポーネントを作成し、エラーを通知してみましょう。

Home.vue
<template>
  <button @click="onError">error</button>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  methods: {
    onError() {
      class ValidationError extends Error {
        constructor(message: string) {
          super(message);
          this.name = "ValidationError";
        }
      }
      throw new ValidationError("ValidationError");
    }
  }
});
</script>

エラー内容

ダッシュボードではエラーのクラス単位で表示されています。

スクリーンショット 2019-12-05 0.23.41.pngスクリーンショット 2019-12-05 0.30.39.png

エラーの詳細ページではOS、ブラウザ、IP、イベントを発火した要素、時間、エラーを吐いたソースの行などが記録されています。

スクリーンショット 2019-12-05 0.29.45.png

スクリーンショット 2019-12-05 0.30.39.png

エラー以外の情報を送信したい

Sentry.captureMessageを使うことで、エラー以外のログを残せます。

captureMessage(message: string, level?: Severity): string;
Sentry.Severity
Sentry.Severity.Critical
Sentry.Severity.Info
Sentry.Severity.Log
Sentry.Severity.Warning
Sentry.Severity.Error
Sentry.Severity.Fatal

APIの通信時間はどれくらいかかってるの?

const startTimeMilliSec = Math.round(performance.now());
const response = await axios.get('https://yesno.wtf/api');
const endTimeMilliSec = Math.round(performance.now());
const message = `
  loadTimeSec: ${(endTimeMilliSec - startTimeMilliSec) / 1000}
  answer: ${response.data.answer}
`;
Sentry.captureMessage(message, Sentry.Severity.Debug);

出力結果は以下の通りです。
API通信のたびに毎回通知が来ても困るので、1秒以上かかった場合などの条件を設けるのがいいかもしれません。

スクリーンショット 2019-12-07 17.56.31.png

Sentryの管理画面の設定

時間を分かりやすくJST/24時間表示に変更しました。

スクリーンショット 2019-12-04 23.58.40.png

Slackに通知する

Settings -> Integrations よりSlackを追加します。

Settings -> Alerts -> Rules -> New Alert Rule から通知ルールを設定します。

以上の設定で通知がSlackに来るようになりました。

スクリーンショット 2019-12-07 18.14.33.png

20
12
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
20
12