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

如何在Vue项目中基于响应错误码返回自定义axios响应

问题根因

当前返回undefined的核心原因是:401错误分支下调用CheckToken接口属于异步操作,你没有返回该异步请求对应的Promise,导致外层Promise链无法感知内部异步操作的执行结果,直接返回undefined。

代码调整方案

1. 修改api.service.js中的get方法

get(resource, slug = "") {
  // 可以直接用普通对象返回,无需构造Response,更方便前端取值,也可保留Response逻辑
  const getCustomRes = (status, statusText) => {
    // 如果要保留Response格式,就返回new Response(JSON.stringify({}), {status, statusText})
    return { status, statusText, data: null }
  }

  return Vue.axios.get(`${resource}/${slug}`)
    .catch((error) => {
      if (error.response?.status == 401) {
        // 401响应处理
        if (resource != "CheckToken") {
          // 这里必须加return,把CheckToken的Promise返回给外层链
          return Vue.axios
            .get("CheckToken") 
            .then((CheckTokenResponse) => {
              if (CheckTokenResponse.data == "OK") {
                // token有效但无接口权限
                return getCustomRes(401, "noAuthorityValid")
              } else {
                // token无效
                return getCustomRes(401, "noTokenValid")
              }
            })
            .catch(() => {
              // CheckToken请求失败,判定token无效
              return getCustomRes(401, "noTokenValid")
            });
        } else {
          // 本身就是CheckToken请求返回401,直接判定token无效
          return getCustomRes(401, "noTokenValid")
        }
      } else {
        // 非401错误,直接返回原始错误对象,也可以按需求统一格式化
        return error
      }
    });
},

核心修改点:

  • 给CheckToken的请求添加return,将其纳入外层Promise链,确保异步结果能传递到调用侧
  • 封装通用的自定义响应生成方法,统一返回格式
  • 新增error.response?.status可选链判断,避免无response对象时报错

2. 组件调用方式保持不变

即可按你预期的逻辑在then中判断状态:

ApiService.get("MyFunction")
  .then((response) => {
    console.log("MyFunction response", response);
    if (response.statusText === "noAuthorityValid") {
      // 弹出无权限提示
      this.$snackbar("you are not authorized for this function")
    } else if (response.statusText === "noTokenValid") {
      // token无效,跳转登录页
      this.$router.push("/login")
    }
    // 其他正常业务逻辑
  })
  .catch((error) => {
    // 仅处理网络异常等未被上述逻辑捕获的错误
    console.log("MyFunction error", error);
  });

如果你需要保留原生Response对象的返回格式,只需要修改getCustomRes方法的实现,调用侧需要通过response.text()或者response.json()获取响应内容即可。

内容的提问来源于stack exchange,提问作者Aurora

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:39:00