我知道这是一个比平时更笼统的问题,但如果我能开始理解如何实现这个关键部分,那就太棒了。
我有一个用 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等。
我读到了处理这种情况的抽象类,但我很难理解如何创建这样一个类
最佳答案
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()
}
关于java - 如何通过改造调用处理来自网络的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61940075/