massphoenix
massphoenix

Reputation: 329

rxJava error catching socketTimeoutException

I have an observable generated from retrofit that I am trying to implement error handling for, specifically connection timeouts. The subscribers on error gets called just fine but the app still crashes with a sockettimeout error. Any advice?

Observable<History> history = api.returnHistoryRX(pair, String.valueOf(unixTime-3600), String.valueOf(unixTime));

history.onErrorReturn(throwable -> null);

subscriber

public void getPriceNow(Observable<List<history>> history, String pair) {
        Timestamp timestamp2;
        timestamp2 = new Timestamp(System.currentTimeMillis());


        history.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(history1 -> {
                    String currentValue;

                    if (history1.size()>0){
                        System.out.println("testing rx");

                    }
                }, e->System.out.println("getPriceNow: error called"));
    }

To Test I am setting the timeout to something unreasonably low with okhttp

    private  OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.MILLISECONDS)
        .readTimeout(30L, TimeUnit.MILLISECONDS)
        .writeTimeout(100L, TimeUnit.MILLISECONDS);

The error chain looks like this:

java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add onError handling.

Caused by: rx.exceptions.OnErrorNotImplementedException: failed to connect

Caused by: java.net.SocketTimeoutException: failed to connect

Upvotes: 2

Views: 3104

Answers (3)

RAINA
RAINA

Reputation: 1012

Try setting up gloable error handler

// If Java 8 lambdas are supported RxJavaPlugins.setErrorHandler(e -> { });

// If no Retrolambda or Jack RxJavaPlugins.setErrorHandler(Functions.emptyConsumer());

Upvotes: 0

hertzon
hertzon

Reputation: 89

add .onExceptionResumeNext {

on observer

Upvotes: 0

N&#225;ndor Előd Fekete
N&#225;ndor Előd Fekete

Reputation: 7098

When you invoke history.onErrorReturn(...), that method returns a new Observable with the appropriate behavior applied. You'll need to use that returned observable where you want the error handling behavior applied. In your case it might be as simple as changing

history.onErrorReturn(throwable -> null); 

to

history = history.onErrorReturn(throwable -> null);

or moving it to where you initialize your history variable.

Upvotes: 2

Related Questions