Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a generic wrapper function for saga error handling?

I would like to create a wrapper that would handle the try-catch clauses in my sagas to make them a bit more concise. So far I have the code below, but it's not working.

export function* withErrorHandler(fn, errorFn) {
  try {
    fn();
  } catch (e) {
    yield put(errorFn(parseError(e)));
  }
}

export function* logoutSaga() {
  yield withErrorHandler(function*() {
    yield put(logoutRequest());
    yield call(api.logout);
    yield localStorage.clear();
    yield put(logoutSuccess());
  }, logoutFailure);
}
like image 486
Eugene Avatar asked May 28 '26 19:05

Eugene


2 Answers

Why do you need a wrapper? Just put it in a try/catch block:

export function* logoutSaga() {
  try {
    yield put(logoutRequest());
    yield call(api.logout);
    yield localStorage.clear();
    yield put(logoutSuccess());
  } catch(e) {
    yield put(logoutFailure(parseError(e)));
  }
}

Additionally, you can eliminate the need to parse errors at all, by wrapping your API functions in a wrapper. For example:

class ApiError {
    constructor(err, helpful) {
        this.original = err;
        this.helpful = helpful;
    }
}

const logout = () => { 
    try {
        return axios.post("accounts/logout/");
    } catch (err) {
        throw new ApiError(err, 'There was a problem logging out.');
    }
}

Then in your error handling functions, you can check if the thrown error is "instanceof ApiError", and display err.helpful to the end user. You can take the constructor of ApiError even further, parse the original error, and modify this.helpful more based on the returned result.

like image 164
ugh StackExchange Avatar answered May 30 '26 08:05

ugh StackExchange


You pass a generator, not a function so you need to call it properly. You should change your wrapper like this

export function* withErrorHandler(fn, errorFn) {
 try {
  yield fn();
 } catch (e) {
...
like image 34
akmed0zmey Avatar answered May 30 '26 08:05

akmed0zmey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!