在axios的catch从句中获取HTTP错误的响应体数据
解决方案
Axios 抛出的错误对象内置了response字段,当请求收到服务器返回的非2xx状态码响应时,该字段会包含完整的响应内容,你需要的自定义错误元数据就存放在response.data属性中。
修改后的代码示例如下:
function (ent) { return axios .post(config.ROOT_API + '/api/backstory/', {new_parent_entity: ent, child_entity: this.entity}) .then(({data}) => { console.log(data) }) .catch((e) => { // 判断是否存在服务器返回的响应 if (e.response) { const errData = e.response.data // 此处即可拿到你定义的错误体内容 console.log(errData) // 示例:获取具体错误提示 console.log(errData.error) // 输出 Circular reference detected } else if (e.request) { // 请求已发出但未收到响应,常见于网络异常、跨域拦截、超时等场景 console.log('请求无响应:', e.request) } else { // 请求配置有误,未成功发出 console.log('请求配置错误:', e.message) } }) }
注意事项
- 不要直接访问
e.response,需要先做存在性判断,避免非响应类错误场景下出现undefined报错。 - 如果你配置了Axios全局响应拦截器,需要确认拦截器中对错误的处理逻辑是否透传了原始错误的
response属性,避免catch中无法拿到对应数据。
内容的提问来源于stack exchange,提问作者metalaureate
相关产品推荐
相关产品推荐

