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.
Apache License 2.0
15.51k stars 3.32k forks source link

Handle `SocketTimeoutException` #287

Closed drayan85 closed 5 years ago

drayan85 commented 6 years ago

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

St4B commented 5 years ago

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)

hernandazevedo commented 5 years ago

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);
        };

    }
}
drayan85 commented 5 years ago

Thank you @St4B & @hernandazevedo