Blog>
Snippets

Error Handling with try/catch in Redux Saga

Use a `try/catch` block within a generator function to handle errors from an API call, demonstrating graceful error recovery in Redux Saga.
import { call, put } from 'redux-saga/effects';
import { apiFetchSomething } from './api'; // Assume this is your API call function

// Saga to fetch data with error handling
function* fetchData(action) {
  try {
    const data = yield call(apiFetchSomething, action.payload); // Execute the API call
    yield put({type: 'FETCH_SUCCESS', data}); // Dispatch success action if API call is successful
  } catch (error) {
    console.error('Fetch error:', error);
    yield put({type: 'FETCH_FAILURE', error}); // Dispatch failure action on error
  }
}
This code defines a Redux Saga generator function named fetchData. It attempts to fetch data using an API call. The try/catch block is used to gracefully handle any errors that may occur during the API call. If the call succeeds, a success action with the fetched data is dispatched to the store. If the call fails, an error is logged to the console, and a failure action with the error details is dispatched, allowing the application to handle the failure appropriately.