【问题标题】:Handling Errors with Custom Axios and redux-saga使用自定义 Axios 和 redux-saga 处理错误
【发布时间】:2020-03-31 12:56:58
【问题描述】:

我的 React 应用程序中有以下管道

saga.js:

function* handleGetTrack(action: ReturnType<typeof selectTrack>) {
  try {
    const getTrackResponse = yield httpGetTrack(action.payload)
    yield console.log(getTrackResponse)

     getTrackResponse.status === 200
       ? yield put(trackSelected(getTrackResponse.data))
       : yield put(selectTrackError('Track Not Found (Get)'))
  } catch (err) {
    if (err instanceof Error && err.stack) {
      yield put(selectTrackError(err.stack))
    } else {
      yield put(selectTrackError('An unknown error occured.'))
    }
  }
}

Api.js

export function httpGetTrack(trackId) {
  return customAxios.get(`${URL}/tracks/${trackId}`)
}

customAxios.js:

export const customAxios = axios.create({
  baseURL: process.env.REACT_APP_API_ENDPOINT,
  timeout: 10000,
})
customAxios.interceptors.response.use(
  function(response) {
    return response
  },

  function(error) {
    const errorResponse = error.response
    if (isTokenExpiredError(errorResponse)) {
      return resetTokenAndReattemptRequest(error)
    }
    return error.response
  }
)

像这样一切正常,事实上在我的 saga.js 中我可以让console.log(getTrackResponse) 很好地打印错误,

但是在 Axios 文档中它说你使用 return Promise.reject(error) 而不是 return error.response

为什么会这样??我做得好还是不好??

【问题讨论】:

    标签: reactjs error-handling axios interceptor redux-saga


    【解决方案1】:

    您是否尝试过使用call 效果?例如:

    import { call } from 'redux-saga/effects';
    
    ...
    
    const getTrackResponse = yield call(httpGetTrack, action.payload);
    
    ...
    

    定义拦截器时,您还应该遵循 Axios 文档

    function(error) {
        const errorResponse = error.response
        ...
        return Promise.reject(error.response);
    }
    

    【讨论】:

      【解决方案2】:
      import Api from './path/to/api'
      import { call, put } from 'redux-saga/effects'
      
      function fetchProductsApi() {
        return Api.fetch('/products')
          .then(response => ({ response }))
          .catch(error => ({ error }))
      }
      
      function* fetchProducts() {
        const { response, error } = yield call(fetchProductsApi)
        if (response)
          yield put({ type: 'PRODUCTS_RECEIVED', products: response })
        else
          yield put({ type: 'PRODUCTS_REQUEST_FAILED', error })
      }
      

      Documentation

      Here is an answer for a similar problem

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-07
        • 1970-01-01
        • 2017-02-21
        • 2018-09-08
        相关资源
        最近更新 更多