【发布时间】:2017-06-30 07:53:39
【问题描述】:
我正在使用 GSON 和 RxJava 进行改造来执行网络请求。我试图弄清楚当 Gson 库无法转换时如何获得响应。
当服务器上发生错误并且响应与 Gson 库尝试将响应转换为的类不匹配时,就会发生这种情况。
一种解决方法是在我们尝试转换之前创建一个拦截器并缓存响应。但这只是糟糕的编程,因为一旦我们开始执行并发请求,问题就会变得难以管理。
服务定义如下:响应类只包含一个状态码和一个称为数据的通用类型。
Retrofit getService() {
return new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(url)
.client(clientBuilder.build())
.build();
}
public Observable<Response<String>> userLogin(String username, String password) {
return getService().create(Account.class)
.login(username, password)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
}
我们在代码中的其他地方创建请求
getService().userLogin(email, password)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onSuccess(), onError());
protected Action1<Response<String>> onSuccess(){
return new Action1<Response<String>>() {
@Override
public void call(Response<String> response) {
// Process the response
}
};
}
protected Action1<Throwable> onError(){
return new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
if (throwable instanceof HttpException) {
ResponseBody body = ((HttpException) throwable).response().errorBody();
// Handle the error
}
}
};
当服务器返回字符串以外的内容时会出现问题。例如对象或数组。这里 GsonConverterFactory 将抛出一个错误,该错误将被 onError 方法捕获。我想知道如何才能得到回应。
返回的 throwable 是 JsonSyntaxException 类型,遗憾的是它不包含 GSON 库尝试转换的原始响应正文。
【问题讨论】: