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

API天气数据获取的错误处理:无效城市名/空输入问题

解决OpenWeatherMap API请求错误捕获失效的问题

问题原因

你当前的代码里,axios.get()返回的是Promise对象,外层的try/catch只能捕获同步代码的错误,而Promise的异步错误无法冒泡到外层同步的try/catch中,所以无效城市名、空输入导致的API错误(比如404、400状态码)不会触发外层的catch块。


解决方案

方案1:给Promise添加.catch()链式调用

直接在axios.get()的.then()后追加.catch(),专门捕获API请求的异步错误:

const searchLocation = (event) => {
  if (event.key === 'Enter') {
    // 修正URL参数格式,移除多余的&符号
    axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${API_KEY}&units=${metric_units}`)
      .then((response) => {
        if (response.data.name) {
          console.log(response.data.name)
          setData(response.data)
        }
      })
      .catch((e) => {
        // 捕获API请求错误:无效城市、空输入、网络异常等
        console.log('请求错误:', e.message)
        // 可在此添加用户提示逻辑,比如"城市名称无效,请重新输入"
      })
    setLocation('')
  }
}

方案2:使用async/await配合try/catch

将函数改为async函数,用await等待请求完成,这样异步错误就能被外层的try/catch捕获:

const searchLocation = async (event) => {
  if (event.key === 'Enter') {
    try {
      // 修正URL参数格式
      const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${API_KEY}&units=${metric_units}`)
      if (response.data.name) {
        console.log(response.data.name)
        setData(response.data)
      }
      setLocation('')
    } catch (e) {
      console.log('请求错误:', e.message)
      // 处理错误逻辑
    }
  }
}

额外优化:提前校验空输入

可以在发起API请求前先校验输入是否为空,避免不必要的请求:

const searchLocation = async (event) => {
  if (event.key === 'Enter') {
    // 校验输入是否为空
    if (!location.trim()) {
      console.log('请输入城市名称')
      return
    }
    try {
      const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${API_KEY}&units=${metric_units}`)
      console.log(response.data.name)
      setData(response.data)
      setLocation('')
    } catch (e) {
      console.log('城市名称无效或请求失败:', e.message)
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:50:43