如何创造传奇的错误处理的通用包装函数?

问题描述 投票:2回答:1

我想创建一个包装,将在处理我的传奇故事在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);
}
reactjs redux redux-saga
1个回答
1
投票

为什么你需要的包装?只要把它放在一个try / catch块:

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更多基于返回的结果。

© www.soinside.com 2019 - 2024. All rights reserved.