js setTimeout 错误捕获
方法一
全局重写 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
方法四
window.onerror = function(message, source, lineno, colno, error) { console.log("捕获到的错误信息是:", message, source, lineno, colno, error); };
有可以给每个异步函数的回调函数中写 try catch ,但是比较繁琐,不建议使用。

浙公网安备 33010602011771号