Search code examples
androiderror-handlingrx-javaretrofit2rx-android

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


Solution

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