Blog>
Snippets

Saga Error Handling Patterns

Provide examples of common error handling patterns in Redux-Saga, focusing on try/catch blocks within sagas to gracefully manage exceptions.
function* fetchResource(resource) {
  try {
    const response = yield call(api.fetch, resource);
    yield put({ type: 'FETCH_SUCCESS', payload: response });
  } catch (error) {
    yield put({ type: 'FETCH_FAILURE', payload: error.message });
  }
}
This code defines a saga generator function named fetchResource. It attempts to fetch a resource using an asynchronous API call within a try block. If the API call succeeds, a FETCH_SUCCESS action is dispatched with the response payload. If the API call fails, a catch block captures the error, and a FETCH_FAILURE action is dispatched with the error message.
function* watchFetchRequests() {
  while (true) {
    const action = yield take('FETCH_REQUEST');
    yield fork(fetchResource, action.payload);
  }
}
This watcher saga waits for FETCH_REQUEST actions. Upon receiving one, it forks a new task to handle the fetch operation by calling the fetchResource saga with the payload of the FETCH_REQUEST action. Using fork allows multiple fetch requests to be handled concurrently.