一、全局捕获 error
window.addEventListener(
'error',
(message, filename, lineNo, colNo, stackError) => {
console.log(message); // 错误信息的描述
console.log(filename); // 错误所在的文件
console.log(lineNo); // 错误所在的行号
console.log(colNo); // 错误所在的列号
console.log(stackError); // 错误的堆栈信息
}
);
二、全局捕获 unhandledrejection
当 Promise 被 reject 且没有 reject 处理器的时候,会触发 unhandledrejection 事件;这可能发生在 window 下,但也可能发生在 Worker 中。 这对于调试回退错误处理非常有用。
window.addEventListener('unhandledrejection', event => {
console.log(event);
});
三、接口异步请求时
这里可以对fetch和XMLHttpRequest进行重新的封装,既不影响正常的业务逻辑,也可以进行错误上报。
XMLHttpRequest 的封装:
const xmlhttp = window.XMLHttpRequest;
const _oldSend = xmlhttp.prototype.send;
xmlhttp.prototype.send = function() {
if (this['addEventListener']) {
this['addEventListener']('error', _handleEvent);
this['addEventListener']('load', _handleEvent);
this['addEventListener']('abort', _handleEvent);
} else {
var _oldStateChange = this['onreadystatechange'];
this['onreadystatechange'] = function(event) {
if (this.readyState === 4) {
_handleEvent(event);
}
_oldStateChange && _oldStateChange.apply(this, arguments);
};
}
return _oldSend.apply(this, arguments);
};
fetch 的封装:
const oldFetch = window.fetch;
window.fetch = function() {
return _oldFetch
.apply(this, arguments)
.then(res => {
if (!res.ok) {
// True if status is HTTP 2xx
// 上报错误
}
return res;
})
.catch(error => {
// 上报错误
throw error;
});
};