Problem: the try-catch insanity
Again, I admit I have done it, we all have done it. Another copy and paste job from some tutorial that written up in 2 minutes for the purpose of learning NOT fit for production code that is littered with try-catch.
Here is a contrived example:
As you can see, this is not very good for our mental healthy, let’s see if we can do it better.
Option 1: try-catch wrapper
As per Unix Error handling principle “If we don’t have anything interesting to say, keep it quiet”. Meaning if we don’t have any value to add to solving the error, let it bubble up to the root error handler which is Option-2 below.
In the case that we don’t want error to bubble up to root Saga, or we are interested in handling in a specific saga, we wrap the saga generator in a safe generator.
onError handler can dispatch an event if we want the error to be handled somewhere else in the code base.
const onError = (err:any) => yield put(actions.requestError(err))
Option 2: Global error handler
So we have to options here:
1. Add an onError function to the middleware option.
2. Chain a catch function at returned promise of sagaMiddleware.run()
Okay thanks for reading if you have any suggestions please PR me on Github.