Blog>
Snippets

Handling Errors with Try/Catch in Sagas

Demonstrate the implementation of error handling within a saga using try/catch blocks, providing a strategy for managing failed operations or API requests.
function* fetchPostsSaga(action) {
  try {
    const posts = yield call(api.fetchPosts);
    yield put({ type: 'FETCH_POSTS_SUCCESS', posts });
  } catch (e) {
    yield put({ type: 'FETCH_POSTS_FAILURE', message: e.message });
  }
}
This saga attempts to fetch posts from an API. If the API call succeeds, it dispatches a FETCH_POSTS_SUCCESS action with the retrieved posts. If the call fails, it catches the error and dispatches a FETCH_POSTS_FAILURE action with the error message.
function* rootSaga() {
  yield takeEvery('FETCH_POSTS_REQUEST', fetchPostsSaga);
}
This is the root saga which listens for FETCH_POSTS_REQUEST actions and triggers the fetchPostsSaga for each action. It uses the takeEvery effect which allows multiple fetchPostsSaga instances to be started concurrently.