You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:27:01