Created
December 3, 2016 18:26
-
-
Save josepot/989354cf34a8186416b14d6783843b9d to your computer and use it in GitHub Desktop.
Sagas: Global Error Handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I usually use the request-sequence pattern | |
// (https://gist.github.com/josepot/cf63578fa81c7dba89ba156e71274537) | |
// And since 99% of the times that a saga errors it's because something | |
// went wrong with a request. That's not the only case when a saga can crash. | |
// The problem is that if there is an unhandled exception is a saga, that | |
// exception gets propagated all the way up to the rootSaga and the root | |
// saga will cancell all watchers... Which can be pretty annoying. | |
// This is one way to avoid such thing from happening: | |
// This is just a silly example on how to deal with a general exception. | |
// I'm sure that in your project you will have a better way to deal | |
// with it. | |
function errorHandler(error, watcher) { | |
console.log('The following unexpected exeption happened.'); | |
console.log(error.message); | |
console.log(error.stack); | |
console.log('Which made the following watcher crash:'); | |
console.log(watcher.toString()); | |
console.log('The watcher has been restarted'); | |
} | |
function* startFaultTolerantWatcher(watcher) { | |
try { | |
yield call(watcher); | |
} catch(e) { | |
errorHandler(e, watcher); | |
yield call(startFaultTolerantWatcher, watcher); | |
} | |
} | |
function* startMainWatchers(...watchers) { | |
yield watchers.map(watcher => call(startFaultTolerantWatcher, watcher)); | |
// This will run the watchers in parallel like `fork` does, but without | |
// forking them. | |
} | |
export default function* rootSaga() { | |
// Whatever non permanent watchers that we need to run on init: | |
// These ones should be able to handle their own exceptions. | |
yield call(initilizeStuff); | |
yield call(getConfigInfo); | |
// ...Whatever | |
// These are the "eternal" watchers. | |
yield call(startMainWatchers, watcher1, watcher2, watcher3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment