前端错误监控
前端错误监控系统在前端开发中是很重要的,毕竟我们的程序运行在用户那里,当用户使用时发生错误,我们可以第一时间收到信息。
这段时间开发了一个前端监控系统,涉及前端错误和性能监控,总结一下前端错误捕获。
前端错误捕获
1.捕获资源加载错误
window.addEventListener('error', function (e) {
console.log(e)
}, true);
2.捕获语法错误
window.onerror = function (msg, url, line, col, error) {
console.log(error)
};
3.捕捉异步错误 (被 reject 且没有 reject 处理器的时候)
window.addEventListener('unhandledrejection', function (e) {
console.log(e)
})
拦截ajax
/*
*拦截浏览器XMLHttpRequest
*参考Ajax-hook(https://github.com/wendux/Ajax-hook)
*/
// intercept ajax
Ajax({
onreadystatechange: function (xhr) {
},
onload: function (xhr) {
},
open: function (arg, xhr) {
},
onerror: function (xhr) {
//An error has occurred here. You can report it
console.log(xhr)
},
})
// rewrite ajax
function Ajax(proxy) {
window.ahrealxhr = window.ahrealxhr || XMLHttpRequest;
XMLHttpRequest = function () {
this.xhr = new window.ahrealxhr;
for (let attr in this.xhr) {
let type = "";
try {
type = typeof this.xhr[attr]
} catch (e) { }
if ("function" === type) {
this[attr] = hookFunction(attr);
} else {
Object.defineProperty(this, attr, {
get: getterFactory(attr),
set: setterFactory(attr)
})
}
}
}
function getterFactory(attr) {
return function () {
let v = this.hasOwnProperty(attr + "_") ? this[attr + "_"] : this.xhr[attr];
let attrGetterHook = (proxy[attr] || {})["getter"]
return attrGetterHook && attrGetterHook(v, this) || v
}
}
function setterFactory(attr) {
return function (v) {
let xhr = this.xhr;
let that = this;
let hook = proxy[attr];
if (typeof hook === "function") {
xhr[attr] = function () {
proxy[attr](that) || v.apply(xhr, arguments);
}
} else {
let attrSetterHook = (hook || {})["setter"];
v = attrSetterHook && attrSetterHook(v, that) || v
try {
xhr[attr] = v;
} catch (e) {
this[attr + "_"] = v;
}
}
}
}
function hookFunction(fun) {
return function () {
var args = [].slice.call(arguments)
if (proxy[fun] && proxy[fun].call(this, args, this.xhr)) {
return;
}
return this.xhr[fun].apply(this.xhr, args);
}
}
return window.ahrealxhr;
}
总结
以上就是前端错误捕捉最精华的部分,拿到错误时可以使用img上传减少用户资源消耗
let img = new Image();
img.src = `请求地址?参数`;
或者使用navigator.sendBeacon()方法进行上报。
欢迎来github谈论,star,watch或者issues.