简体   繁体   中英

Retrofit2 + RxJava2 Global handling errors

How to check a network connection and is the server available for all requests, using retrofit2 and 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?

I have more api requests, for example one of this:

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. 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

And use it as follow :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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