LoginSignup
114
114

More than 5 years have passed since last update.

GoogleアナリティクスでJavascriptエラー収集

Last updated at Posted at 2014-06-27

(追記 2014/10/25)
※ コメントで教えていただいたのですが、今はUniversal Analyticsで例外トラッキングというのがあるそうです。
https://developers.google.com/analytics/devguides/collection/analyticsjs/exceptions

きっかけ

  • ユーザーの環境によってエラーが出たり出なかったり…
  • テスト用の実機用意するのも大変、てかデバッグ死ぬ
  • ならユーザー側のJavascriptエラーを全部集めればいいじゃん!
  • でもそのためにサーバ立てたりするのは大変
  • よし、Googleアナリティクスでさくっとエラーを収集だ

実装

ポイントはwindow.onerror。エラーが起きた時にGoogleアナリティクスにイベントを投げるようにしている。

index.html
window.onerror = function(message, url, lineNumber) {
    var fileName = url.match(".+/(.+?)([\?#;].*)?$")[1]; //URLからファイル名を取得
    var message
        =  fileName + ':' + lineNumber
        + " - "+ message + ",\n"
        + 'userAgent:' + window.navigator.userAgent;
        ga('send', 'event', 'JSError', fileName, message);
};

ついでに本番との切り分けもしとく。これは上のコードの前に置く。

var ga_uid = (location.host == "www.localhost.com")
    ? "UA-xxxxxxxx-x"  //本番
    : "UA-xxxxxxxx-x"; //テスト
ga('create', ga_uid, window.location.hostname);

キャプチャ画像

こんな感じでエラーが収集できる
Screen Shot 2014-06-28 at 0.11.53.png

参考リンク

114
114
2

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
114
114