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

VueJS与Axios错误处理异常:捕获的错误对象属性缺失问题

登录流程错误抛出问题分析与解决

问题原因

  • 原生Error对象的实例默认仅包含name和message两个可枚举属性,当你捕获AxiosError后创建新的Error实例时,AxiosError特有的status、code等属性不会自动被继承或附加到新实例上。
  • 若你在抛出新Error时仅传递了错误消息,没有手动将AxiosError的其他属性挂载到新Error上,组件的catch块自然只能拿到原生Error的默认属性。

解决方法

方法1:直接抛出原AxiosError

不需要自定义错误时,直接将捕获到的AxiosError抛出,组件就能获取完整的错误对象:

// auth.service.js
async login(credentials) {
  try {
    const response = await axios.post('/api/login', credentials);
    return response.data;
  } catch (error) {
    throw error; // 直接抛出原AxiosError
  }
}

方法2:自定义错误类继承Error

需要区分错误类型时,创建自定义错误类,继承原生Error并附加AxiosError的关键属性:

// auth.service.js
// 自定义认证错误类
class AuthError extends Error {
  constructor(message, axiosError) {
    super(message);
    this.name = 'AuthError';
    // 复制AxiosError的核心属性
    this.status = axiosError.response?.status;
    this.code = axiosError.code;
    this.response = axiosError.response;
    // 保留错误堆栈
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, AuthError);
    }
  }
}

async login(credentials) {
  try {
    const response = await axios.post('/api/login', credentials);
    return response.data;
  } catch (error) {
    throw new AuthError(error.message, error);
  }
}

方法3:给原生Error实例附加属性

不想定义新类的话,直接在新Error实例上挂载需要的属性:

// auth.service.js
async login(credentials) {
  try {
    const response = await axios.post('/api/login', credentials);
    return response.data;
  } catch (error) {
    const customError = new Error(error.message);
    // 手动添加AxiosError的关键属性
    customError.status = error.response?.status;
    customError.code = error.code;
    customError.response = error.response;
    throw customError;
  }
}

组件中获取错误属性

无论用哪种方法,组件的catch块都能访问到扩展后的错误属性:

// 组件内登录方法
async handleLogin() {
  try {
    await authService.login(this.credentials);
    // 登录成功逻辑
  } catch (error) {
    console.log('错误状态码:', error.status);
    console.log('Axios错误码:', error.code);
  }
}

内容的提问来源于stack exchange,提问作者Mr.P

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:12