Blog>
Snippets

Graceful Error Handling in Sagas

This code demonstrates using try/catch blocks within sagas to manage errors from API calls or external events. It includes how to catch errors, perform cleanup or rollback actions, and dispatch failure actions to the Redux store.
import { call, put } from 'redux-saga/effects';
import { fetchData } from '../api';
import { fetchDataSuccess, fetchDataFailure } from '../actions';

function* fetchResourceSaga(action) {
  try {
    // Attempt to call the API
    const data = yield call(fetchData, action.payload);
    // Dispatch a success action with the fetched data
    yield put(fetchDataSuccess(data));
  } catch (e) {
    // If an error occurs, dispatch a failure action
    yield put(fetchDataFailure(e.message));
  }
}
This saga attempts to fetch data using the 'fetchData' API call. If the call succeeds, it dispatches a 'fetchDataSuccess' action with the data. If the call fails, it catches the error and dispatches a 'fetchDataFailure' action with the error message.
import { all, fork } from 'redux-saga/effects';
import { watchFetchResource } from './watchers';

export default function* rootSaga() {
  yield all([
    // Fork the watcher saga that is responsible for handling fetch actions
    fork(watchFetchResource)
  ]);
}
This root saga uses 'all' to combine multiple sagas if necessary. In this example, it forks a watcher saga 'watchFetchResource' responsible for initiating the 'fetchResourceSaga' upon specific actions.