【问题标题】:Accessing the server response when an error occurs in my saga request在我的 saga 请求中发生错误时访问服务器响应
【发布时间】:2020-05-27 21:03:10
【问题描述】:

我正在使用库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
    }
}


【问题讨论】:

    标签: redux request axios redux-saga http-error


    【解决方案1】:

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

    响应的路径是:

    action.error.response.data

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多