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

自定义错误未正常打印:axios请求抛出ERROR时提示Error is not defined

问题诊断与修复方案

嘿,我一眼就看到问题所在了——你犯了一个很容易忽略的拼写错误!

核心问题:错误构造函数拼写错误

你代码里写的throw new ERROR('Unable To Find That Address');中,JavaScript的原生错误构造函数是Error(首字母大写E,其余小写),而不是全大写的ERROR。因为不存在名为ERROR的全局对象,所以代码执行到这里时会抛出Error is not defined的引用错误,你的自定义错误自然没法按预期输出。

修复步骤

1. 修正错误构造函数

把错误行改成正确的拼写即可:

throw new Error('Unable To Find That Address');

2. (可选)优化错误区分逻辑(推荐)

如果想在catch块里更精准地识别自定义错误,可以给错误对象添加自定义属性,避免和其他类型的错误混淆:

axios.get(geocodeUrl)
  .then((response) => {
    if(response.data.status === 'ZERO_RESULTS') {
      const addressError = new Error('Unable To Find That Address');
      // 添加自定义标记,方便后续判断
      addressError.errorType = 'ADDRESS_NOT_FOUND';
      throw addressError;
    }
    console.log(JSON.stringify(response.data, undefined ,2));
  })
  .catch((e)=> {
    if(e.code === 'ENOTFOUND') {
      console.log('Unable to contact api servers');
    } else if(e.errorType === 'ADDRESS_NOT_FOUND') {
      // 精准处理地址未找到的情况
      console.log(e.message);
    } else {
      console.log(e.message);
      console.log("xyz");
    }
  });

为什么"xyz"能正常打印?

当抛出ERROR这个未定义的构造函数时,会触发一个ReferenceError,这个错误会进入catch块。因为它的code不是ENOTFOUND,所以会走到最后的else分支,打印错误消息(也就是Error is not defined)和"xyz"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:57:52