如何在Retrofit Response为Succesfull时添加GSON CallAdapterFactory

时间:2016-03-18 09:36:14

标签: android rx-java rx-android retrofit2

我有一个REST服务器,我的问题是每当我的响应不成功时我想从响应主体解析错误并将其显示给用户(将错误信息传递给调用的Activity)

@Named("rest_api")
@Singleton
@Provides
Interceptor provideRESTInterceptor(final UserManager userManager) {
    return new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            String token = userManager.getJwt();

            Request request = original.newBuilder()
                    .header("Accept", "application/json")
                    .header("Authorization", "Bearer "+token)
                    .method(original.method(), original.body())
                    .build();

            Log.i(LOG_TAG, "REQUEST URL "+request.uri());
            Response response = chain.proceed(request);

            if(!response.isSuccessful()) {
                // How do i send this error to my Activity.

                APIError apiError = new APIError(response.code(),response.body().string());
            }

            // Customize or return the response
            return response;
        }
    };
}

我正在使用RxJavaConverter

@Named("rest_api")
@Singleton
@Provides
Retrofit provideRESTRetrofit(@Named("rest_api")OkHttpClient client, Converter.Factory converter, CallAdapter.Factory rxJava) {
    return new Retrofit.Builder()
            .baseUrl(PUBLIC_PRODUCTION_URL)
            .client(client)
            .addCallAdapterFactory(rxJava)
            .addConverterFactory(converter)
            .build();
}

自Retrofit 2.0以来,即使响应不成功,它也会尝试将给定GSON的数据转换为(POJO),从而抛出错误,我丢失了错误的实际消息。

1 个答案:

答案 0 :(得分:2)

作为@david:mihola建议它有效,使用Retrofit Response对象我能够实现这一点。

Response<MyObject> response;
if(response.isSucessful) {
   MyObject obj = response.body();
} else {
  // You can process your error message from the reponse
}

它确实让我免于批量手册GSON解析