为什么在redux-saga生成器中无法捕获错误?

时间:2019-03-14 19:37:07

标签: reactjs react-redux axios redux-saga

这是store / store.js

...

const initSagaMiddleware = createSagaMiddleware();

const middlewares = [initSagaMiddleware, fetchPhotosMiddleware, putPhotoMiddleware];
const middlewareEnhancer = applyMiddleware(...middlewares);

...

initSagaMiddleware.run(rootSaga);

export default store;

sagas / api-saga.js

export default function* rootSaga() {
    yield all([
        photoWatcher()
    ]);
}

function* photoWatcher() {
    yield takeEvery(PUT_PHOTO, putPhotoWorker);
}

function* putPhotoWorker(action) {
    try {
        const payload = yield call(putPhoto, action.urlParams, action.body);
        yield put({ type: PHOTO_UPDATED, payload });
    } catch (err) {
        yield put({ type: API_ERROR_PUT_PHOTO, payload: err });
    }
}

和services / api.js

export function putPhoto(urlParams, body) {
    return axios.put('/abc/' + urlParams.key + '/def/' + urlParams.id + '/edit', body)
        .then(res => {
            return res.data;
        })
        .catch(err => err);
}

我的问题是:即使我从api调用中收到错误,也要put而不是PHOTO_UPDATED代替API_ERROR_PUT_PHOTO。我究竟做错了什么?如何捕捉错误?

2 个答案:

答案 0 :(得分:1)

问题是您试图两次捕获同一错误。只需从putPhoto函数中删除捕获就可以了。

export function putPhoto(urlParams, body) {
    return axios.put('/abc/' + urlParams.key + '/def/' + urlParams.id + '/edit', body)
        .then(res => {
            return res.data;
        });
}

答案 1 :(得分:0)

then函数中的catchputPhoto承诺均产生了try语句。因此,我放弃了try...catch,而是现在使用if...else语句。像这样:

function* putPhotoWorker(action) {
    const payload = yield call(putPhoto, action.urlParams, action.body);
    if (isResponseTypeWhatIExpected) {
        yield put({ type: PHOTO_UPDATED, payload });
    } else {
        yield put({ type: API_ERROR_PUT_PHOTO, payload });
    }
}