使用try-catch块仍出现Axios未处理错误异常的原因排查
Axios错误无法被try-catch捕获的常见原因
未在异步函数中用
await调用Axios
要是你调用Axios时没加await,或者直接用.then/.catch的同时套了try-catch,try-catch根本抓不到异步错误。比如错误写法:function fetchData() { try { axios.get('/api/data'); // 没加await,try-catch无效 } catch (err) { console.log(err); } }改成异步函数加
await就正常了:async function fetchData() { try { await axios.get('/api/data'); } catch (err) { console.log(err); } }Axios响应错误未被正确抛出
服务器返回4xx、5xx这类非2xx状态码时,Axios默认会触发reject,但如果你的全局响应拦截器里处理了错误却没重新抛出,后续的try-catch就拿不到错误。比如错误写法:axios.interceptors.response.use( res => res, err => { console.log('拦截到错误'); // 没把错误抛出去,后续catch抓不到 } );必须把错误重新reject:
axios.interceptors.response.use( res => res, err => { console.log('拦截到错误'); return Promise.reject(err); } );错误发生在try-catch作用域之外
要是Axios请求放在setTimeout、事件回调这类独立异步上下文里,try-catch覆盖不到这个范围。比如:async function fetchData() { try { setTimeout(() => { axios.get('/api/data'); // 这里的错误try-catch管不着 }, 1000); } catch (err) { console.log(err); } }要么把try-catch挪到回调内部,要么用Promise封装定时器:
async function fetchData() { await new Promise(resolve => setTimeout(resolve, 1000)); try { await axios.get('/api/data'); } catch (err) { console.log(err); } }
内容的提问来源于stack exchange,提问作者user19734079
相关产品推荐
相关产品推荐

