如何通过翻新呼叫处理来自网络的错误

问题描述 投票:2回答:1

我知道这是一个比平常更普遍的问题,但是如果我将开始理解我如何实现这一关键部分,那将是惊人的。

我有一个使用RxJava处理的简单改造电话:

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

并且在我的存储库中,我正在处理响应:

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

我如何处理所有可能的情况?

例如:网络错误/加载/空响应/错误的api等。

我了解了处理这种情况的抽象类,但是我很难理解如何创建这样的类

java android retrofit2 rx-java2
1个回答
1
投票

该throwable代表不同的异常。根据异常对它们进行classify,您将可以检查Wheather是HttpException还是JsonSyntaxExceptionNetwork Exception。如下所示。

 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()
}
© www.soinside.com 2019 - 2024. All rights reserved.