Kim
Kim

Reputation: 5425

how to handle redux saga error in the wrapper?

This is the Normal Way:

function* saga1() {
  try {
    // do stuff
  } catch (err) {
    // handle err
  }
}

function* saga2() {
  try {
  } catch (err) {
  }
}

function* wrapper() {
  yield [
    takeLatest('saga1', saga1),
    takeLatest('saga2', saga2),
  ];
}

This is Expected Way:

function* saga1() {
}

function* saga2() {
}

function* wrapper() {
  try {
    takeLatest('saga1', saga1),
    takeLatest('saga2', saga2),
  } catch (err) {
    // handle errors
  }
}

Is there anyway to achieve above way to handle errors? Using normal way sometimes leading to repeatedly handle same error.

Upvotes: 1

Views: 364

Answers (1)

Vladislav Ihost
Vladislav Ihost

Reputation: 2187

Easiest way for this case is fork as using parallel dynamic effect in saga. Of course, it is not real thread, but way to write sequence of asynchronous operations.

Let see your example in depth. Construction like yield [ takeA(), takeB() ] supposes that you delegate A&B operation to saga workflow with supplied callback. In other words, execution of wrapper is done for this moment, so try/catch is not appropriate.

Is alternative you can fork as parallel dynamic effect for two or more independent saga-processes, and make infinite loop in which of them.

Code:

function* proc1() {
  while(true) {
    yield call(() => new Promise(resolve => setTimeout(resolve, 1500)));
    throw new Error('Err1')
  }
}

function* proc2() {
  while(true) {
    yield call(() => new Promise(resolve => setTimeout(resolve, 2000)));
    throw new Error('Err2')
  }
}

function* watchLoadRequest() {
  try {
    yield [call(proc1), call(proc2)]
  } catch(err) {
    console.log('@@ERROR@@', err);
  }
}

Of course, you should implement custom business login in parallel procedures. If you need a persistent/shared state between them, use object argument with appropriate fields.

Upvotes: 1

Related Questions