評估例外狀況

您可以評估例外狀況,監控網頁上發生的當機或錯誤類型。本頁說明如何使用 gtag.js 將例外狀況傳送至 Google Analytics (分析)。

導入作業

如果發生錯誤,請將例外狀況事件傳送至 Google Analytics (分析):

gtag('event', 'exception', {<exception_parameters>});

其中 <exception_parameters> 是一或多個參數/值組合。請以半形逗號分隔每個組合。例如,這個指令會傳送不嚴重的錯誤例外狀況。

gtag('event', 'exception', {
  'description': 'error_description',
  'fatal': false   // set to true if the error is fatal
});

例外狀況參數

下表列出例外狀況參數:

參數名稱 資料類型 必要 說明
description string 錯誤說明。
fatal boolean true 表示嚴重錯誤。

範例

假設下方函式如下:

function divide(x, y) {
  if (y === 0) {
    throw "Division by zero";
  }
  return x/y;
}

如果除數 y 為零,下列程式碼會將 exception 事件傳送至 Google Analytics (分析):

var x = document.getElementById('x').value;
var y = document.getElementById('y').value;

try {
  var r = divide(x, y);
} catch(err) {
  gtag('event', 'exception', {
    'description': err,
    'fatal': false
  });
}