React Native-获取API正确的错误处理

时间:2018-08-31 12:43:10

标签: javascript react-native rxjs observable

我对React Native来说还很陌生,并且在没有学习前端正确的错误处理的情况下,已经拥有7年的经验。我一直在为此特定应用程序编写前端和后端,并且遇到了需要澄清的情况。

我在后端建立了一个基本的RBAC层,在到达数据库端点之前进行了各种检查。在此问题中,RBAC检查用户是否为管理员。如果不是,则返回如下所示的401状态:

rbac.check(role, type, {
    user: user,
    [identifier]: resourceId
  }, (err, result) => {
    if (!result) {
      return res.status(401).json({
        success: false,
        message: 'not authorized to access'
      })
    } else {
      return next();
    }
  }
);

据我所读的文章,这是正确的方法(可能是错误的)。问题发生在我的前端,这是使用Fetch API的React Native应用程序。我有一个thunk,它调用了一个服务方法,该服务方法又调用了通用的http服务方法。我将提取API包裹在下面可见的地方:

// Thunk Code 
const _getOrganizations = (organizations) => {
  return {
    type: Types.TYPES_ORGANIZATIONS_SET,
    payload: organizations
  };
};

export const getOrganizations = (userId) => {
  return dispatch => {
    return OrganizationService.getAll(userId)
      .map(
        _data => {
          if (!_data['success'] && !_data['organizations']) {
            _data['organizations'] = [];
          }

          dispatch(_getOrganizations(_data['organizations']));
          return _data;
        }, _error => { return _error; }
      )
  };
};

// Service method:
getAll(userId) {
  return Http.$get(Constants.ENDPOINT_USER, userId, Constants.POSTFIX_ORGANIZATIONS);
}

// Http Service
$get(endpoint, id, postfix, auxId) {
  let _postfix = (typeof postfix === 'undefined' || postfix === null) ? '' : postfix;
  let _auxId = (typeof auxId === 'undefined' || auxId === null) ? '' : '/' + auxId;

  return Observable.defer(() => {
    return Observable.fromPromise(
      fetch(this.apiUrl + endpoint + id + _postfix + _auxId, {
        method: 'get',
        headers: this._headers()
      })
      .then(this._checkStatus)
      .then(res => res.json()));
    }
  );
}

如您所见,promise在链中具有checkStatus方法。我添加了它,因为这是我在如何使用提取API的所有示例中都看到的内容。我的checkStatus方法如下:

/**
 * Error Handling
 */
_checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  } else {
    let error = new Error(response.statusText);
    error.response = response;
    throw error;
  }
}

从后端返回401时,else语句正在运行,引发错误,这在React Native领域中向用户引发了一个红色错误屏幕。显然这不是我想要发生的事情。

我现在基本上不了解处理此类问题的最佳实践,因此尽管我可以想出各种方法来解决此问题,但这并不意味着我就是采取最佳做法。

我已经完成或考虑过的事情:

  1. 在检查状态方法中,我只是删除了抛出错误行并返回了响应。

这对我来说意义不大,因为这种状态检查是通用的,应该可以处理许多可能发生的情况。我真的不在乎RBAC响应,因为服务器上从未真正请求过数据。

  1. 在这种情况下,我考虑过添加更多条件来检查401并返回响应。

那真的不能解决红屏问题,因为同一错误会发生,例如500。可能是部分问题出在我的代码上,而我没有正确处理错误。

是的,我知道使用Observables并非明智之举。我最初是从Angular的世界做到这一点的,并认为拥有它会很棒。我了解到,使用redux可以消除在网络请求中使用可观察的大多数好处。我计划稍后删除代码,但现在不能这样做。

任何帮助和建议将不胜感激。预先感谢。

0 个答案:

没有答案