Blog>
Snippets

Error Handling in Saga Patterns

Demonstrate a robust error handling strategy within a Redux Saga task, using `try/catch` blocks within generator functions to gracefully manage failed operations.
import { call, put } from 'redux-saga/effects';
Import necessary effects from redux-saga.
function* fetchResourceSaga(action) {
  try {
    const resource = yield call(apiFetch, action.payload);
    yield put({type: 'FETCH_SUCCESS', resource});
  } catch (error) {
    yield put({type: 'FETCH_FAILURE', error: error.message});
  }
}
Defines a saga to fetch a resource. It uses try/catch to handle fetch operation: on success, dispatches FETCH_SUCCESS with the resource, on failure, dispatches FETCH_FAILURE with the error.
const apiFetch = async (payload) => {
  // Simulate API fetch operation
  if(payload.shouldFail) {
    throw new Error('Fetch failed');
  }
  return { data: 'Resource data' };
};
Mock API fetch function to simulate successful and failed fetch operations based on input payload.