拦截API错误

时间:2018-06-27 16:08:03

标签: react-admin

我正在使用带有标准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] 
    ...

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

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

  

当API后端返回错误时,数据提供者应抛出一个Error对象。此对象应包含带有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状态代码应让用户继续(通过返回已解决的承诺)或注销它们(通过返回被拒绝的承诺)。