【问题标题】:Handle all types of Retrofit errors properly with rxjava使用 rxjava 正确处理所有类型的改造错误
【发布时间】:2018-08-10 13:27:28
【问题描述】:

我是RxjavaRetrofit 的新手,我正在寻求使用rxjavarxbinding 处理Retrofit 中所有可能状态的最佳正确方法,其中包括:

  1. 没有互联网连接。
  2. 来自服务器的空响应。
  3. 成功响应。
  4. 错误响应并显示类似Username or password is incorrect的错误消息。
  5. connection reset by peers 等其他错误。

【问题讨论】:

标签: android retrofit2 rx-java2 rx-binding


【解决方案1】:

我为每个重要的失败响应都有异常子类。 异常以Observable.error() 传递,而值通过流传递而没有任何包装。

1) 没有互联网 - ConnectionException

2) Null - 只是 NullPointerException

4) 检查“错误请求”并抛出 IncorrectLoginPasswordException

5) 任何其他错误都只是 NetworkException

您可以使用onErrorResumeNext()map() 映射错误

例如

从 Web 服务获取数据的典型改造方法:

public Observable<List<Bill>> getBills() {
    return mainWebService.getBills()
            .doOnNext(this::assertIsResponseSuccessful)
            .onErrorResumeNext(transformIOExceptionIntoConnectionException());
}

保证响应正常的方法,否则抛出适当的异常

private void assertIsResponseSuccessful(Response response) {
    if (!response.isSuccessful() || response.body() == null) {
        int code = response.code();
        switch (code) {
            case 403:
                throw new ForbiddenException();
            case 500:
            case 502:
                throw new InternalServerError();
            default:
                throw new NetworkException(response.message(), response.code());
        }

    }
}

IOException 表示没有网络连接所以我抛出 ConnectionException

private <T> Function<Throwable, Observable<T>> transformIOExceptionIntoConnectionException() {
    // if error is IOException then transform it into ConnectionException
    return t -> t instanceof IOException ? Observable.error(new ConnectionException(t.getMessage())) : Observable.error(
            t);
}

为您的登录请求创建新方法,该方法将检查登录名/密码是否正常。

最后还有

subscribe(okResponse -> {}, error -> {
// handle error
});

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 2020-05-26
    • 2021-12-21
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    相关资源
    最近更新 更多