android10 / Android-CleanArchitecture

This is a sample app that is part of a series of blog posts I have written about how to architect an android application using Uncle Bob's clean architecture approach.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Handle `SocketTimeoutException`

drayan85 opened this issue · comments

How to handle the SocketTimeoutException from the Data Layer and throw as NetworkConnectionException.class Exception?

In your sequence of observables, that may throw SocketTimeoutException, you can do something like that:

.onErrorResumeNext(throwable -> throwable instanceof SocketTimeoutException ? Observable.error(new NetworkErrorException(throwable)) : Observable.error(throwable)

I agree with @St4B, my solution for that problem is something like this:

.onErrorResumeNext(ErrorResumeHandler.handleApiCallErrors())

See below:

public class ErrorResumeHandler {
    public static <T> Function<Throwable, Observable<T>> handleApiCallErrors() {
        return whenExceptionThenReplace(
                new Pair<>(HttpException.class, new ServicesDownException()),
                new Pair<>(SocketTimeoutException.class, new NetworkException()),
                new Pair<>(UnknownHostException.class, new NetworkException()));
    }

    public static <T> Function<Throwable, Observable<T>> whenExceptionThenReplace(Pair<Class<?>, Throwable>... pairListException) {
        return t -> {
            Observable<T> response = null;

            for (Pair<Class<?>, Throwable> pair : pairListException) {
                if(pair.first.isInstance(t))
                    response = Observable.error(pair.second);
            }

            if( response != null )
                return response;
            else
                return Observable.error(t);
        };

    }
}