Nuxt.js中Axios无法正确捕获API错误信息求助
解决Nuxt.js中Axios无法捕获API返回错误详情的问题
我完全懂你的困扰——Axios默认会把服务器返回的错误信息封装在自己的错误对象里,直接打印err只能看到它生成的通用提示,而你需要的API返回的具体错误数据其实藏在err.response.data里。
问题根源
当请求返回4xx/5xx这类错误状态码时,Axios会抛出一个自定义错误对象,这个对象的结构里包含了完整的响应细节:
err.message:Axios自动生成的通用错误描述(比如你看到的"Request failed with status code 400")err.response:服务器返回的完整响应实体,其中**err.response.data就是Postman里显示的那个JSON格式的错误内容**
修改后的代码示例
把你的catch逻辑改成下面这样,就能拿到想要的错误详情了:
await axios .post( "API LINK", { email: user.email, password: "123456", name: user.name, dob: user.dob ?? null, gender: user.gender ?? null, profileImage: imageUrl ?? user.profileImage, userType: user.userType } ) .then(res => { console.log("success"); console.log(res); }) .catch(err => { console.log('fail'); // 优先获取API返回的错误详情 if (err.response) { console.log(err.response.data); // 这里可以直接提取信息提示用户,比如: // alert(err.response.data.error.message); } else { // 处理网络中断等没有服务器响应的情况 console.log(err.message); } })
额外小提示
- 一定要加上
err.response的判断,避免因为网络错误(比如请求根本没发出去)导致Cannot read property 'data' of undefined的报错 - 如果项目里有很多请求,你也可以在Nuxt的
plugins/axios.js里配置全局错误拦截器,统一处理所有请求的错误逻辑,不用每个请求都写重复代码
内容的提问来源于stack exchange,提问作者Purinut




