当我的 saga 请求发生错误时访问服务器响应

Accessing the server response when an error occurs in my saga request

我正在使用库 redux-saga-requests 进行网络通信和高级状态管理。按照 the documentation 的指导,我设置了一个全局错误处理程序,以在服务器请求超时或用户遇到连接问题时显示通知。

但是,当我收到服务器错误(例如 500)时,我无法在我的操作中访问响应。服务器响应不存在。

有没有办法访问此对象,同时仍保持在 redux-saga 的范围和规则内?

这是初始商店设置 - 请注意 onErrorSaga 不会给我网络响应,所以我不妨使用默认行为 - 发送一个后缀 _ERROR 的操作被我的减速器捕获:


function* onErrorSaga(error, action) {
    console.log('error?', error)
    console.log('action?', action)

    // None of these contain the server response, 
    // just the error message and stack thrown by the client.

    yield { error }
}

function* rootSaga(axiosInstance) {
    yield createRequestInstance({
        driver: {
            default: createAxiosDriver(axiosInstance),
        },
        onError: onErrorSaga,
    })
    yield watchRequests()
}

const configureStore = initialState => {
    const sagaMiddleware = createSagaMiddleware()
    const middlewares = [thunkMiddleware, requestsPromiseMiddleware({ auto: true }), sagaMiddleware, trackingMiddleware]
    const store = createStore(rootReducer, initialState, composeWithDevTools(applyMiddleware(...middlewares)))

    sagaMiddleware.run(rootSaga, axiosInstance)

    return store
}

export const configureStoreAsync = () => {
    return new Promise((resolve, reject) => {
        const store = configureStore()
        store
            .dispatch(fetchAppInitialization())
            .then(result => resolve(store))
            .catch(e => reject(store))
    })
}

以下是我当前处理状态错误的方式(然后由通知组件显示):


import { CLOSE_NOTIFICATION } from '../actions/actions.notification'

export default (state = [], action) => {
    if (action.type.endsWith('_ERROR')) {
        return {
            type: 'warning',
            title: action.error.message,
            message: `${action.error.stack.substring(0, 200)}...`,
            open: true,
            timestamp: new Date(),
        }
    }
    switch (action.type) {
        case CLOSE_NOTIFICATION:
            return {
                ...state,
                open: false,
            }
        default:
            return state
    }
}


事实证明这比我想象的要容易得多。 action 对象实际上包含服务器响应。

响应路径为:

action.error.response.data