Blog>
Snippets

Error Handling with `try-catch` in Redux Saga

Illustrate the implementation of error handling within a Redux Saga using `try-catch` block, focusing on robust management of failed API calls.
import { call, put, takeLatest } from 'redux-saga/effects';
import axios from 'axios';

// Action Types
const FETCH_DATA_REQUEST = 'FETCH_DATA_REQUEST';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';
Defines the action types and imports necessary modules.
function fetchDataApi() {
  return axios.get('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.data)
    .catch(error => { throw error; });
}
Defines the API call function using axios. It throws an error if the call fails, allowing the saga to catch it.
function* fetchDataSaga() {
  try {
    const data = yield call(fetchDataApi);
    yield put({ type: FETCH_DATA_SUCCESS, data });
  } catch (error) {
    yield put({ type: FETCH_DATA_FAILURE, error: error.message });
  }
}
Saga generator function that attempts to fetch data. It uses a try-catch block to handle any errors that occur during the API call.
function* watchFetchDataSaga() {
  yield takeLatest(FETCH_DATA_REQUEST, fetchDataSaga);
}
Watches for the FETCH_DATA_REQUEST action and runs fetchDataSaga. Uses takeLatest to cancel any ongoing saga tasks if a new FETCH_DATA_REQUEST action is dispatched.