Blog>
Snippets

Handling Specific HTTP Errors with Redux-Saga

A Redux-Saga that specifically catches HTTP 500 errors and retries the request, ignoring other types of errors.
import { call, put, takeEvery } from 'redux-saga/effects';
import axios from 'axios';

const FETCH_DATA = 'FETCH_DATA';
const FETCH_SUCCESS = 'FETCH_SUCCESS';
const FETCH_FAILED = 'FETCH_FAILED';
const RETRY_FETCH = 'RETRY_FETCH';

function fetchApi() {
  return axios.get('https://your-api-endpoint.com/data');
}

function* fetchDataSaga(action) {
  try {
    const response = yield call(fetchApi);
    yield put({ type: FETCH_SUCCESS, payload: response.data });
  } catch (error) {
    if (error.response && error.response.status === 500) {
      // Specific handling for HTTP 500 errors
      console.log('HTTP 500 Error, retrying...');
      yield put({ type: RETRY_FETCH, payload: action.payload });
    } else {
      // Handling for other types of errors
      console.log('Fetch Failed:', error.message);
      yield put({ type: FETCH_FAILED, error: error.message });
    }
  }
}

function* watchFetchData() {
  yield takeEvery(FETCH_DATA, fetchDataSaga);
}
This code defines a Redux-Saga that listens for the FETCH_DATA action. When this action is dispatched, fetchDataSaga is executed. It attempts to fetch data from an API. If an HTTP 500 error occurs during the fetch, the saga logs the error and dispatches the RETRY_FETCH action to retry the fetch operation. For other errors, it logs the error and dispatches the FETCH_FAILED action.
import { all } from 'redux-saga/effects';

function* rootSaga() {
  yield all([
    watchFetchData(),
    // you can add more watchers here
  ]);
}

export default rootSaga;
This code defines the rootSaga which combines all individual sagas, including watchFetchData, into a single entry point for the Redux-Saga middleware to run. This setup is crucial for initializing the sagas in your application.