【问题标题】:Why cannot catch error in redux-saga generator?为什么无法在 redux-saga 生成器中捕获错误?
【发布时间】:2019-08-05 19:57:55
【问题描述】:

这里是 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 });
    }
}

和服务/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 调用中得到错误,redux-saga putting PHOTO_UPDATED 而不是 API_ERROR_PUT_PHOTO。我究竟做错了什么?如何捕捉错误?

【问题讨论】:

  • 问题是你在putPhoto函数中发现了错误。只需取下锁扣,它应该可以工作。大概吧。
  • 不。它没有工作:/
  • API 会报错吗?
  • 当然。 400 错误请求。
  • 如果在putPhoto函数中留下promisecatch,错误发生时会调用catch回调吗? (把console.log或者smth放进去检查)。

标签: reactjs react-redux axios redux-saga


【解决方案1】:

问题是您试图两次捕获相同的错误。只需从putPhoto 函数中删除catch,它应该可以工作。

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

【讨论】:

    【解决方案2】:

    thencatchputPhoto 函数中的承诺都会导致 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 });
        }
    }
    

    【讨论】:

    • 我把我的答案放在这里,如果有人遇到这样的问题,以便他们可以解决。我不接受它,因为它不是对问题的直接回答。
    猜你喜欢
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 2016-10-27
    • 2018-06-15
    相关资源
    最近更新 更多