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

Axios不同错误场景下如何统一打印触发错误的请求URL?

Axios错误信息自定义优化方案

问题背景

我封装了一个Axios GET请求工具函数,想在请求出错时给错误信息添加自定义内容,显示实际请求的协议、主机和路径,而非打印完整错误信息。目前遇到的情况是:

  • 针对超时或证书类错误,error.request是RedirectableRequest类型,需通过_currentRequest获取数据,代码如下:
this.axios
  .get(endpoint, { params, ...config})
  .catch((error) => {
    const customMessage = `\nFailed GET ${error.request._currentRequest.protocol}//${error.request._currentRequest.host}${error.request._currentRequest.path}`
    error.message += customMessage
    throw error
  })
  • 针对404这类HTTP状态码错误,error.request是ClientRequest类型,直接访问属性即可,代码如下:
const customMessage = `\nFailed ${error.request.method} ${error.request.protocol}//${error.request.host}${error.request.path}`

感觉这种实现方式不够优雅,想知道有没有优化方案,另外会不会是我的Axios配置有问题?我使用的是Axios 1.4版本,1.3.2版本也存在同样问题。


优化方案

核心思路是统一请求信息的获取逻辑,无需区分error.request的类型,同时避免依赖_currentRequest这类私有属性(下划线开头的属性属于内部实现,后续版本可能变动)。

方案1:从error.config解析完整请求地址

Axios错误对象的config字段保存了完整的请求配置,直接解析其中的url即可提取所需信息,这是最稳定的方式:

this.axios
  .get(endpoint, { params, ...config})
  .catch((error) => {
    const fullUrl = new URL(error.config.url);
    // 优先从config取方法,避免request实例中方法缺失
    const method = error.config.method?.toUpperCase() || 'GET';
    const customMessage = `\nFailed ${method} ${fullUrl.protocol}//${fullUrl.host}${fullUrl.pathname}${fullUrl.search}`;
    error.message += customMessage;
    throw error;
  })

该方法不受错误类型影响,只要error.config存在(Axios错误基本都会包含这个字段),就能稳定获取请求地址。

方案2:兼容两种error.request类型的通用逻辑

如果一定要从error.request获取信息,可以做属性兼容处理:

this.axios
  .get(endpoint, { params, ...config})
  .catch((error) => {
    // 优先取_currentRequest,不存在则用原始request
    const req = error.request._currentRequest || error.request;
    const method = error.config.method?.toUpperCase() || req.method || 'GET';
    const customMessage = `\nFailed ${method} ${req.protocol}//${req.host}${req.path}`;
    error.message += customMessage;
    throw error;
  })

关于配置的说明

你遇到的情况不是配置问题,是Axios的正常行为:

  • 当请求未完成就失败(如超时、证书错误),若开启了自动重定向(默认开启),error.request会是RedirectableRequest实例
  • 当请求已收到响应(如404、500),error.request会是最终的ClientRequest实例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:43:21