方法一
全局重写 setTimeout
代码语言:javascript复制function overrideSetTimeout(fn){
return function(callback, delay, params){
var _callback = function(){
try{
callback();
}catch(err){
console.log(err)
}
}
fn(_callback,delay);
}
}
setTimeout = overrideSetTimeout(setTimeout);
setTimeout(function(){
throw new Error("hhh")
},1000);
参考
方法二
封装为 promise,通过 promise.catch 捕获,或 promise 全局错误捕获
代码语言:javascript复制const p3 = () => new Promise((reslove, reject) => {
setTimeout(() => {
reject('async error');
})
});
function main3() {
p3().catch(e => console.log(e));
}
main3();
方法三
封装为 promise,通过 async await 调用,通过 try catch 捕获
代码语言:javascript复制const fetchFailure = () => new Promise((resolve, reject) => {
setTimeout(() => {// 模拟请求
if(1) reject('fetch failure...');
})
})
async function main () {
try {
const res = await fetchFailure();
console.log(res, 'res');
} catch(e) {
console.log(e, 'e.message');
}
}
main(); // fetch failure... e.message