简体   繁体   English

Retrofit2 + RxJava2全局处理错误

[英]Retrofit2 + RxJava2 Global handling errors

How to check a network connection and is the server available for all requests, using retrofit2 and rxjava2? 如何使用Retrofit2和rxjava2检查网络连接以及服务器是否可用于所有请求?

I can check the “server available” by sending a request to my server url, but can I check the network connection by sending a request to google.com or to another “good” website? 我可以通过向服务器网址发送请求来检查“服务器可用”,但是我可以通过向google.com或另一个“良好”网站发送请求来检查网络连接吗?

I have more api requests, for example one of this: 我有更多的api请求,例如其中之一:

compositeDisposable.add(RetrofitClient
            .getApi()
            .somemethod()
            .map(response -> {
                Data data = null;
                if (response.isSuccessful()) {
                    data = response.body();
                } else {
                    data = new Data();
                    data.setResponseCode(response.code())
                }
                return data;
            })
            .onErrorReturnItem(new Data())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(this::checkResponse());

How to check these errors, which I wrote, for all requests in order not to duplicate the code? 为了不重复代码,如何检查所有请求的这些错误? Thanks. 谢谢。

Call RxJavaPlugins.setErrorHandler in onCreate of your application class. 在应用程序类的onCreate中调用RxJavaPlugins.setErrorHandler For example: 例如:

    RxJavaPlugins.setErrorHandler(e -> {
        if ((e instanceof IOException) || (e instanceof SocketException)) {
            // handle exception
            return;
        }
    });

You could use lift method which allow you to implement your own operator for your case ApiErrorOperator 您可以使用lift方法,该方法允许您为案例ApiErrorOperator实现自己的运算符

And use it as follow : 并按如下所示使用它:

@Override
  public @NonNull Observable<List<Category>> fetchCategories() {
    return this.service
      .categories()
      .lift(apiErrorOperator())
      .map(CategoriesEnvelope::categories)
      .subscribeOn(Schedulers.io());
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM