Java 如何通过改装呼叫处理来自网络的错误
我知道这是一个比平常更普遍的问题,但如果我开始理解如何实现这一关键部分,那将是一件令人惊讶的事情 我用RxJava处理了一个简单的改装调用:Java 如何通过改装呼叫处理来自网络的错误,java,android,retrofit2,rx-java2,Java,Android,Retrofit2,Rx Java2,我知道这是一个比平常更普遍的问题,但如果我开始理解如何实现这一关键部分,那将是一件令人惊讶的事情 我用RxJava处理了一个简单的改装调用: public interface MoviesApi { @GET("3/movie/popular") Single<Movies> getAllMovies( @Query("api_key") String apiKey ); } public interface MoviesApi{ @
public interface MoviesApi {
@GET("3/movie/popular")
Single<Movies> getAllMovies(
@Query("api_key") String apiKey
);
}
public interface MoviesApi{
@获取(“3/电影/流行”)
单人电影(
@查询(“api_键”)字符串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();
}
})
ApiService.getMoivesApi().getMovies(API_键)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribowith(新的可处置SingleObserver(){
@凌驾
成功时公开作废(电影){
电影。设置值(电影);
}
@凌驾
公共无效申报人(可丢弃的e){
e、 printStackTrace();
}
})
我如何处理所有可能的案件
例如:网络错误/加载/空响应/错误的api等
我读过处理这种情况的抽象类,但我很难理解如何创建一个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()
}