Blog>
Snippets

Handling Errors in Attached Forks

Demonstrate error propagation from an attached child saga back to the parent saga using try-catch blocks within Redux-Saga.
import { fork, take, put, call, all } from 'redux-saga/effects';
import api from './api'; // Assume this is an API module for making fetch requests
Import necessary effects and the API module for making requests.
function* fetchResource(resource) {
  try {
    const data = yield call(api.fetch, resource);
    yield put({ type: 'FETCH_SUCCESS', data });
  } catch (error) {
    yield put({ type: 'FETCH_FAILURE', error });
    throw error; // Re-throw the error to propagate it up to the parent saga
  }
}
A child saga that fetches a resource and dispatches a success or failure action. It re-throws errors to propagate them to the parent saga.
function* fetchAll() {
  try {
    yield all([fork(fetchResource, 'users'), fork(fetchResource, 'comments')]);
  } catch (error) {
    console.error('Error in one of the child sagas:', error);
    // Additional error handling logic can be placed here
  }
}
The parent saga that forks child sagas to fetch resources in parallel. Catches errors thrown by child sagas.
function* rootSaga() {
  // Start the fetchAll saga
  yield take('FETCH_START');
  yield call(fetchAll);
}
Root saga which starts the fetchAll saga upon receiving a 'FETCH_START' action.