【问题标题】:Intercept api errors拦截 api 错误
【发布时间】:2018-06-27 16:08:03
【问题描述】:

我正在使用带有标准 crud 选项的 react-admin,如果错误是 401(例如令牌超时),我想对 RA/CRUD_GET_LIST_FAILURE(以及将来的所有其他人)做出反应以注销用户

我该怎么做呢? 在自定义请求中,我有自己的 sagas 来处理 catch 部分并正确完成工作。

如果我尝试像这样拦截RA/CRUD_GET_LIST_FAILURE

function * loadingErrorRA (action) {
  var e = action.payload;
  console.error('loadingError',action);
  if(action.error === "Unauthorized"){ 
  //I can't find a better way because I don't have access to the fetch response object in here
    yield put(userLogout());
    yield put(showNotification('Disconnected','warning'));
  } else {
    yield put(showNotification('Error '+action.error,'warning'));
  }
}

function * errorLoadingSaga() {
  yield takeLatest('RA/CRUD_GET_LIST_FAILURE', loadingErrorRA);
}

我有一个空白屏幕并弹出一个错误:

ListController.js:417 Uncaught TypeError: Cannot read property 'list' of undefined
    at Function.mapStateToProps [as mapToProps] (ListController.js:417)
    at mapToPropsProxy (wrapMapToProps.js:43)
    at handleNewPropsAndNewState (selectorFactory.js:34)
    at handleSubsequentCalls (selectorFactory.js:67)
    at pureFinalPropsSelector (selectorFactory.js:74)
    at Object.runComponentSelector [as run] (connectAdvanced.js:26)
    at Connect.componentWillReceiveProps (connectAdvanced.js:150)
    at callComponentWillReceiveProps (react-dom.development.js:11527)
   ....
index.js:2178 The above error occurred in the <Connect(TranslatedComponent(undefined))> component:
    in Connect(TranslatedComponent(undefined)) (created by List)
    in List (created by WithStyles(List))
    in WithStyles(List) (at SalesByOrganismList.js:40)
    in div (at SalesByOrganismList.js:39)
    in SalesByOrganismList (created by WithPermissions)
    in WithPermissions (created by Connect(WithPermissions))
    in Connect(WithPermissions) (created by getContext(Connect(WithPermissions)))
    ...

And then saga catch it with :
index.js:2178 uncaught at loadingErrorRA TypeError: Cannot read property 'list' of undefined
    at Function.mapStateToProps [as mapToProps] 
    ...

感谢您的帮助

【问题讨论】:

    标签: react-admin


    【解决方案1】:

    https://marmelab.com/react-admin/DataProviders.html#error-format

    当 API 后端返回错误时,数据提供者应该抛出一个错误对象。此对象应包含一个带有 HTTP 响应代码(404、500 等)的状态属性。 React-admin 检查此错误代码,并将其用于身份验证(以防 401 或 403 错误)。此外,react-admin 在屏幕上以临时通知的形式显示错误消息。

    还有https://marmelab.com/react-admin/Authentication.html#catching-authentication-errors-on-the-api

    每次 API 返回错误时,都会使用 AUTH_ERROR 类型调用 authProvider。再一次,由您决定哪些 HTTP 状态代码应该让用户继续(通过返回已解决的承诺)或注销它们(通过返回拒绝的承诺)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      相关资源
      最近更新 更多