Blog>
Snippets

Saga Error Propagation

Illustrate how to propagate errors from one saga to another, allowing for complex error handling strategies across multiple sagas.
function* childSaga() {
  try {
    // Simulating an API call
    const data = yield call(apiCall);
    // Success logic here
  } catch (error) {
    // Propagating the error to the parent saga
    throw new Error('Failed in childSaga', { cause: error });
  }
}
This is the child saga where an API call or any other operation might fail. If an error occurs, it is caught in the catch block and then re-thrown with additional context (e.g., specifying it failed in childSaga), so the saga that called this saga (parent saga) can handle it.
function* parentSaga() {
  try {
    // Call the child saga
    yield call(childSaga);
    // If child saga succeeds, continue with the parent saga logic
  } catch (error) {
    // Handle error propagated from childSaga
    console.error('Error caught in parentSaga:', error.message);
    // Error handling logic for parent saga here
  }
}
This is the parent saga that calls the child saga. It tries to run the child saga and catches any errors that are re-thrown from the child saga. This allows for a centralized error handling strategy where errors from multiple child sagas can be handled in their parent saga.