zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

js setTimeout 错误捕获

2023-02-18 16:33:38 时间

方法一

全局重写 setTimeout

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 全局错误捕获

const p3 = () =>  new Promise((reslove, reject) => {
  setTimeout(() => {
    reject('async error');
  })
});

function main3() {
  p3().catch(e => console.log(e));
}
main3();

方法三

封装为 promise,通过 async await 调用,通过 try catch 捕获 

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