我正在使用GSON和RxJava進行改造以執行網絡請求。我試圖找出如何獲得響應時,Gson庫無法轉換它。處理改造2 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庫試圖轉換的原始響應體。