处理Retrofit 2 RX中的错误 [英] Handle errors in Retrofit 2 RX
问题描述
我的请求应获取POJO的JSON或JSON描述的错误(可以是无效的请求字段,服务器问题等).
My request should get either JSON for POJO or JSON described error(can be invalid request fields, server problems and so on).
但是在订户中进行的改装只给我Throwable.如何找出网络错误,什么是http代码,并获取带有错误的JSON?
But retrofit in subscriber gives me only Throwable. How can I find out is that a network error, what is http code, and get JSON with error?
private class ProjectListSubscriber extends Subscriber<ProjectListResponse> {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
//is that a network? http code? convert json to error POJO?
}
@Override
public void onNext(ProjectListResponse projectListResponse) {
updateProjectList(projectListResponse.getProjectList());
}
}
推荐答案
由于您使用的是RxJava,因此在出现网络错误的情况下将调用onError
,并且与端点相关的错误是Response
的一部分.
如果发生错误,请检查throwable是否为
Since you are using RxJava, onError
is called in case of network errors and endpoints related error are part of the Response
.
In case of error, check if the throwable is an instance of HttpException
public void onError(Throwable e) {
if (e instanceof HttpException) {
如果检查为真,则您的请求中有错误.将throwable强制转换为HttpException
,并且访问权限是成员.例如.
if the check is true, the you have an error in your request. Cast the throwable to HttpException
, and access is members. E.g.
((HttpException) e).response().errorBody()
如果检查为false
,则说明与网络相关的错误.
if the check is false
then you have a network related error.
这篇关于处理Retrofit 2 RX中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!