我想知道是否有人有全局处理JavaScript错误并将它们从客户端浏览器发送到服务器的经验。
我想我的观点很清楚,我想知道客户端发生的每一个异常、错误、编译错误等,并将它们发送给服务器报告它们。
我主要使用MooTools和head.js (JS端)和Django作为服务器端。
我想知道是否有人有全局处理JavaScript错误并将它们从客户端浏览器发送到服务器的经验。
我想我的观点很清楚,我想知道客户端发生的每一个异常、错误、编译错误等,并将它们发送给服务器报告它们。
我主要使用MooTools和head.js (JS端)和Django作为服务器端。
当前回答
不要尝试使用第三方服务,而是尝试自己的服务。
错误处理程序可以捕获以下场景:
无法捕获Uncaught TypeError 无法捕获未捕获的ReferenceError,例如:var.click() TypeError可以被捕获 可以捕获语法错误 可以捕获ReferenceError
捕捉Javascript错误:
window.addEventListener('error', function (e) {
//It Will handle JS errors
})
捕获AngularJS错误:
app.config(function ($provide) {
$provide.decorator('$exceptionHandler', function ($delegate) {
return function (exception, cause) {
//It will handle AngualarJS errors
}
})
})
其他回答
我会查看window.onerror
例子:
window.onerror = function(message, url, lineNumber) {
//save error and send to server for example.
return true;
};
请记住,返回true将阻止触发默认处理程序,返回false将让默认处理程序运行。
不要尝试使用第三方服务,而是尝试自己的服务。
错误处理程序可以捕获以下场景:
无法捕获Uncaught TypeError 无法捕获未捕获的ReferenceError,例如:var.click() TypeError可以被捕获 可以捕获语法错误 可以捕获ReferenceError
捕捉Javascript错误:
window.addEventListener('error', function (e) {
//It Will handle JS errors
})
捕获AngularJS错误:
app.config(function ($provide) {
$provide.decorator('$exceptionHandler', function ($delegate) {
return function (exception, cause) {
//It will handle AngualarJS errors
}
})
})
如果你的网站使用谷歌分析,你可以做我做的:
window.onerror = function(message, source, lineno, colno, error) {
if (error) message = error.stack;
ga('send', 'event', 'window.onerror', message, navigator.userAgent);
}
上面代码的一些注释:
For modern browsers, the full stack trace is logged. For older browsers that don't capture the stack trace, the error message is logged instead. (Mostly earlier iOS version in my experience). The user's browser version is also logged, so you can see which OS/browser versions are throwing which errors. That simplifies bug prioritization and testing. This code works if you use Google Analytics with "analytics.js", like this. If you are using "gtag.js" instead, like this, you need to tweak the last line of the function. See here for details.
代码就绪后,你可以这样查看用户的Javascript错误:
In Google Analytics, click the Behavior section and then the Top Events report. You will get a list of Event Categories. Click window.onerror in the list. You will see a list of Javascript stack traces and error messages. Add a column to the report for your users' OS/browser versions by clicking the Secondary dimension button and entering Event Label in the textbox that appears. The report will look like the screenshot below. To translate the OS/browser strings to more human-readable descriptions, I copy-paste them into https://developers.whatismybrowser.com/useragents/parse/