简体   繁体   中英

Redux Saga stops after error

I'm combining a set of Sagas, ( some takeEvery and takeLatest ) from different modules and using yield all(sagas) to combine them all in RootSaga.

Everything works, without issue. I catch errors inside the Sagas themselves. But, now the requirement is to catch errors at RootSaga level too, in any case, someone misses catching a problematic part.( Actually, I'm working on boilerplate for a multi-team project. )

I see, if someone is not using try catch to catch a problematic part, then the error is propagated and Saga completely stops working after that. Sagas won't watch anything thereafter.

What I want to do is, let other Sagas run without issues and RootSaga to be working thereafter, keep watching as usual. How can I achieve this?

export default function* rootSaga() {
    yield all(sagas);
}

For v1 use

rootSagaTask.toPromise().catch(e => {

});

When you run the rootSaga you are getting back a task. That task has a done property which is a promise. So:

const rootSagaTask = reduxSagaMiddleware.run(rootSaga);

rootSagaTask.done.catch(error => {
  // Error here is a fatal error.
  // None of the sagas down the road caught it.
});

After much thinking about this problem, I implemented my own middleware function. Like:

Middleware function:

 * @function errorFallback
 * @param {CallableFunction} sagaFunction
 * @param {object} action
 * @description
 * * Captured exceptions which is occurred from saga function.
 * * Whenever any exception occurred from saga functions, whole sagas will be destroyed.
 * * We can use this function to save sagas from die.
 * @example
 *    export function* getSagaData() {
 *      yield all([
 *        takeLatest('GET_SAGA_DATA', errorFallback, getSaga),
 *      ]);
 *    }
 */

function* errorFallback(sagaFunction, action) {
  try {
    yield sagaFunction(action);
  } catch (error) {
    // exception log to your server
  }
}

export default errorFallback;

Uses

export function* loadSampleSaga() {
  try {
    const response = yield post('/create', {
      name: 'test',
      salary: '123',
      age: '23',
    });
    yield put(sampleSuccessAction());
  } catch (err) {
    yield put(sampleFailureAction());
    throw err;
  }
}

export function* getSampleSaga() {
  yield all([takeLatest('GET_SAMPLE_SAGA_DATA', errorFallback, loadSampleSaga)]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM