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

如何在Axios中处理错误并获取WeatherStack API的错误信息?

解决Axios调用WeatherStack API时无法获取业务错误信息的问题

你遇到的问题根源在于:WeatherStack API查询无效城市时,返回的是200状态码的正常响应(不属于HTTP错误范畴),但响应数据里会包含error字段说明业务层面的错误。此时Axios不会触发catch块,你的代码直接访问res.data.current会因current不存在抛出TypeError,这个错误进入catch块后自然没有error.response(因为不是HTTP请求错误)。

解决方案

需要先检查API返回的业务错误,再处理响应数据;同时在catch块中区分不同类型的错误:

const axios = require("axios");

async function getWeather(city) {
  try {
    const res = await axios({
      method: "get",
      url: `http://api.weatherstack.com/current`,
      params: {
        access_key: "XXXXXXXXXXX",
        query: city,
        units: "m",
      },
      headers: {
        "Content-Type": "application/json",
      },
    });

    // 优先检查API返回的业务错误
    if (res.data.error) {
      throw new Error(res.data.error.info);
    }

    const temp = res.data.current.temperature;
    const precip = res.data.current.precip;
    const feels = res.data.current.feelslike;
    const desc = res.data.current.weather_descriptions[0];

    console.log(
      `${desc}. It is currently ${temp} degrees out. It feels like ${feels} degrees. There is ${precip}% chance of rain.`
    );
  } catch (error) {
    // 分类型处理错误
    if (error.message) {
      // 业务错误(自行抛出的API错误信息)
      console.log("查询失败:", error.message);
    } else if (error.response) {
      // HTTP状态码错误(如密钥无效、权限不足等)
      console.log("HTTP错误:", error.response.status, error.response.data);
    } else if (error.request) {
      // 网络错误,未收到API响应
      console.log("网络错误:无法连接到WeatherStack API");
    } else {
      // 其他未知错误
      console.log("未知错误:", error.message || error);
    }
  }
}

getWeather("helloworld");

关键修改说明

  1. 提前检查业务错误:在访问current字段前,先判断res.data.error是否存在,存在则抛出包含API错误信息的异常,让catch块统一处理。
  2. 多场景错误处理:catch块中区分业务错误、HTTP错误、网络错误和未知错误,确保每种情况都能输出清晰的提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:01:30