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

如何在Axios Get请求中正确捕获错误?ReactJS+Redux天气应用场景

解决React+Redux调用OpenWeatherMap API的错误提示问题

我来帮你搞定城市不存在时的错误提示问题!咱们一步步完善代码,实现清晰的错误捕获和用户友好提示。

1. 补全Action中的错误处理逻辑

首先,你需要完善catch块的逻辑,正确提取OpenWeatherMap返回的错误信息。当城市不存在时,API会返回404状态码,响应体的message字段会明确提示"city not found"。咱们把这个信息传递到Redux的action里:

export const FETCH_WEATHER = 'FETCH_WEATHER';
export const FETCH_WEATHER_ERROR = 'FETCH_WEATHER_ERROR';

export function fetchWeather(city) {
  const url = `${ROOT_URL}&q=${city}`;
  const request = axios.get(url);

  return (dispatch) => {
    request
      .then(({ data }) => {
        // 成功获取数据时,清空之前的错误提示
        dispatch({ type: FETCH_WEATHER_ERROR, payload: null });
        dispatch({ type: FETCH_WEATHER, payload: data });
      })
      .catch((error) => {
        let errorMessage = '获取天气信息失败,请稍后重试';
        // 区分API业务错误和网络错误
        if (error.response && error.response.data) {
          errorMessage = error.response.data.message;
        }
        dispatch({ 
          type: FETCH_WEATHER_ERROR, 
          payload: errorMessage 
        });
      });
  };
}

2. 在Reducer中管理错误状态

接下来修改你的weather reducer,添加错误状态的管理,把错误信息存在state中:

import { FETCH_WEATHER, FETCH_WEATHER_ERROR } from '../actions/index';

const initialState = {
  data: [],
  error: null
};

export default function weatherReducer(state = initialState, action) {
  switch (action.type) {
    case FETCH_WEATHER:
      return {
        ...state,
        data: [...state.data, action.payload],
        error: null // 新搜索成功时清除旧错误
      };
    case FETCH_WEATHER_ERROR:
      return {
        ...state,
        error: action.payload
      };
    default:
      return state;
  }
}

3. 在组件中渲染错误提示

最后,在你的搜索组件或者天气展示组件里,从Redux state中取出错误信息,展示给用户:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchWeather } from '../actions/index';

class SearchBar extends Component {
  state = { term: '' };

  onFormSubmit = (e) => {
    e.preventDefault();
    this.props.fetchWeather(this.state.term);
    this.setState({ term: '' });
  };

  render() {
    return (
      <div className="search-container">
        {/* 错误提示区域 */}
        {this.props.error && (
          <div className="error-alert">
            ⚠️ {this.props.error}
          </div>
        )}
        <form onSubmit={this.onFormSubmit}>
          <input
            type="text"
            value={this.state.term}
            onChange={(e) => this.setState({ term: e.target.value })}
            placeholder="输入城市名称搜索天气"
          />
          <button type="submit">搜索</button>
        </form>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    error: state.weather.error // 这里的weather对应你在store中注册的reducer名称
  };
};

export default connect(mapStateToProps, { fetchWeather })(SearchBar);

你可以给错误提示加些自定义样式,比如:

.error-alert {
  color: #dc3545;
  background-color: #f8d7da;
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 15px;
}

额外细节说明

  • 错误类型区分:代码同时处理了API业务错误(比如城市不存在)和网络错误(比如断网),给用户不同的提示信息。
  • 错误清空逻辑:每次发起新搜索时会清空旧错误,避免旧提示干扰新操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:01:25