ScrapeW
ScrapeW

Reputation: 529

How to handle error from network with retrofit calls

I know it's a more general question than usual, but It would be amazing if I will start to understand how I implement this crucial part.

I have simple retrofit call that I handle with RxJava:

public interface MoviesApi {
    @GET("3/movie/popular")
    Single<Movies> getAllMovies(
            @Query("api_key") String apiKey
    );
}

And in my repository I am handling the response:

     ApiService.getMoivesApi().getMovies(API_KEY)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(new DisposableSingleObserver<AllMovies>() {
                        @Override
                        public void onSuccess(Movies Movies) {
                            movies.setValue(movies);
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                        }
                    })

How can I handle all the possible cases?

For example: network error/loading/empty response/wrong api etc..

I read about abstract class that handle this cases, but I have hard time to understand how to create this such a class

Upvotes: 3

Views: 372

Answers (1)

vikas kumar
vikas kumar

Reputation: 11018

That throwable represents different exceptions. classify them based on the exceptions and you will be able to check wheather if it's a HttpException or a JsonSyntaxException or Network Exception. something like below.

 private fun convertToCause(cause: Throwable): String {
    return when (cause) {
        is JsonEncodingException -> "Some json exception happened"
        is IndexOutOfBoundsException -> "Empty response"
        is HttpException -> {
            processException(cause)
        }
        is UnknownHostException -> "Not connected to internet"
        else -> "Something went wrong"
    }
}

fun processException(cause: HttpException){
   //here get the error code from httpexception and the error message and return 
   //cause.response().errorBody()
   //cause.code()
   //convert to json or something or check the error codes and return message accordingly
   return cause.message()
}

Upvotes: 3

Related Questions