代码之家  ›  专栏  ›  技术社区  ›  Eugene

如何为saga错误处理创建通用包装函数?

  •  2
  • Eugene  · 技术社区  · 7 年前

    我想创建一个包装器来处理我的故事中的try-catch子句,使它们更加简洁。到目前为止,我有下面的代码,但它不工作。

    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);
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Blue    7 年前

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

    此外,通过将API函数包装在包装器中,可以完全消除解析错误的需要。例如:

    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.');
        }
    }
    

    然后在错误处理函数中,可以检查抛出的错误是否为“ instanceof ApiError err.helpful 给最终用户。您可以使用 ApiError 更进一步,解析原始错误,并修改 this.helpful 更多基于返回的结果。

        2
  •  1
  •   akmed0zmey    6 年前

    传递的是生成器,而不是函数,因此需要正确调用它。你应该像这样换包装纸

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