如何通过改造调用处理来自网络的错误
How to handle error from network with retrofit calls
我知道这是一个比平时更笼统的问题,但如果我能开始理解我是如何实现这个关键部分的,那就太棒了。
我有一个用 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();
}
})
如何处理所有可能的情况?
例如:网络error/loading/emptyresponse/wrongapi等
我阅读了有关处理这种情况的摘要 class,但我很难理解如何创建这样一个 class
throwable 代表不同的异常。 根据异常对它们进行分类,您将能够检查它是 HttpException 还是JsonSyntaxException 或 网络异常。如下所示。
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()
}
我知道这是一个比平时更笼统的问题,但如果我能开始理解我是如何实现这个关键部分的,那就太棒了。
我有一个用 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();
}
})
如何处理所有可能的情况?
例如:网络error/loading/emptyresponse/wrongapi等
我阅读了有关处理这种情况的摘要 class,但我很难理解如何创建这样一个 class
throwable 代表不同的异常。 根据异常对它们进行分类,您将能够检查它是 HttpException 还是JsonSyntaxException 或 网络异常。如下所示。
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()
}