一、捕获的错误类型
二、捕获方式
三、错误上报相关问题
Access-Control-Allow-Origin
的响应头;Reporter
函数添加一个采样率;
function needReport (sampling){ // sampling: 0 - 1 return Math.random() <= sampling; } Reporter.send = function(errInfo, sampling) { if(needReport(sampling || 1)){ Reporter._send(errInfo); } };
try..catch,如果要使用请使用尽量干净的作用域;
// 简单可跨域 function report() { (new Image()).src="http://post.error.com?data=xxx" }
// navigator.sendBeacon(url, data); navigator.sendBeacon(‘http://post.error.com‘, ‘data=xxxxx‘); // data 可以传递 string 类型,那么后端接口里接到的请求,Content-Type 为 text/plain,就当字符串处理data
// 此方法可用于满足统计和诊断代码的需要,可以批量发送数据,并且浏览器保证它不卡渲染线程,在页面 load/unload 事件里处理异步动作而不影响渲染,并且天然跨域。缺点只是兼容性了
function reportData(url, data) { if (navigator.sendBeacon) { navigator.sendBeacon(url, data); } else { (new Image()).src = `${url}?data=${data}` } } export default reportData;
window.addEventListener("error", function(e) { var eventType = [].toString.call(e, e); if (eventType === "[object Event]") { // 过滤掉运行时错误 // 上报加载错误 可以获取资源加载错误 console.log(ev.target); report(ev) } }, true );
window.onerror = function (msg, url, lineNo, columnNo, error) { // 捕捉错误 console.log(msg, url, lineNo, columnNo, error) }
window.addEventListener("unhandledrejection", function (event) { // 捕获违背catch的reject console.log(event) console.log(event.reason); event.preventDefault(); // window.addEventListener(‘error‘)捕获资源加载错误。因为它也能捕获js运行时错误,为避免重复上报js运行时错误,此时只有event.srcElement inatanceof HTMLScriptElement或HTMLLinkElement或HTMLImageElement时才上报 });
//window.onerror和window.addEventListener(‘error‘)的异同 //相同点是都可以捕获到window上的js运行时错误。 //区别是1.捕获到的错误参数不同 // 2.window.addEventListener(‘error‘)可以捕获资源加载错误,但是window.onerror不能捕获到资源加载错误
ps: 感谢巨人的肩膀使我们看的更远
原文:https://www.cnblogs.com/webcabana/p/13131769.html