简体   繁体   English

如何使用 retrofit 调用处理来自网络的错误

[英]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:我有使用 RxJava 处理的简单 retrofit 调用:

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..例如:网络错误/加载/空响应/错误 api 等。

I read about abstract class that handle this cases, but I have hard time to understand how to create this such a class我读到了处理这种情况的抽象 class ,但我很难理解如何创建这样的 class

That throwable represents different exceptions.那个 throwable 代表不同的异常。 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 .根据异常它们进行分类,您将能够检查它是否是HttpExceptionJsonSyntaxExceptionNetwork 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()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM