Blog>
Snippets

Saga Error Handling with Try/Catch

Explain how to use a try/catch block within a saga to gracefully handle API request failures, including retrying the request or dispatching an action to update the application state with error information.
function* fetchUserData(action) {
  try {
    const data = yield call(Api.fetchUser, action.payload.userId);
    yield put({ type: 'FETCH_USER_SUCCESS', data });
  } catch (error) {
    yield put({ type: 'FETCH_USER_FAILURE', error });
    // Optionally retry the request
    // yield call(delay, 1000);
    // yield call(fetchUserData, action);
  }
}
This code snippet demonstrates how to use a try/catch block within a Redux-Saga generator function to handle API request failures gracefully. When the `fetchUserData` saga is invoked with an action, it attempts to fetch user data using `Api.fetchUser`. If the request is successful, it dispatches a `FETCH_USER_SUCCESS` action with the fetched data. If the request fails, it catches the error and dispatches a `FETCH_USER_FAILURE` action with the error information instead. The commented-out lines show how one might retry the request after a delay.