衡量异常
您可以通过发送异常事件来衡量网页上发生的崩溃或错误的数量和类型。本页介绍了如何使用 gtag.js 向 Google Analytics 发送异常。
实施步骤
发生错误时,向 Google Analytics 发送“exception”事件:
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 |
布尔值 |
否 |
如果错误很严重,则设为 true 。 |
示例
以下面的函数为例:
function divide(x, y) {
if (y === 0) {
throw "Division by zero";
}
return x/y;
}
如果除数 y 为零,以下代码将向 Google Analytics 发送“exception”事件:
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
});
}
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2024-09-13。
[null,null,["最后更新时间 (UTC):2024-09-13。"],[[["Google Analytics can track website errors and crashes using exception events sent via gtag.js."],["`gtag('event', 'exception', {\u003cexception_parameters\u003e})` is the core function to send exception data, including an optional description and fatality status."],["An example demonstrates how to capture and send exceptions occurring within a JavaScript `try...catch` block."]]],["Exception events, used to track web page crashes and errors, are sent to Google Analytics via the `gtag('event', 'exception', {\u003cexception_parameters\u003e});` command. `\u003cexception_parameters\u003e` include 'description' (error details) and 'fatal' (boolean indicating if the error is fatal). When an error is detected, a `gtag` event can be sent. An example uses a `try...catch` block to intercept division-by-zero errors and trigger the `gtag` event.\n"]]