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 ,但是比较繁琐,不建议使用。
分类:
javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南