首页 > 解决方案 > 如果发生 Gson 错误,如何返回空模型

问题描述

我在我的 Android 应用程序中使用 Retrofit+Gson。有时我会遇到这样的异常:

预期为 BEGIN_OBJECT,但在第 1 行第 1 列路径为字符串 $ retrofit2.converter.gson.GsonResponseBodyConverter.convert

当服务器响应错误请求时,我不希望我的应用程序崩溃。

如果发生此类错误,有没有办法返回一个空的 ResponseBody (Model)?

        val okHttpClient = OkHttpClient()
            .newBuilder()
            .readTimeout(5, TimeUnit.MINUTES)
            .writeTimeout(5, TimeUnit.MINUTES)
            .addInterceptor(TokenInterceptor(preferencesHelper))
            .addInterceptor(ClientInterceptor())
            .addInterceptor(mHttpLoggingInterceptor)
            .build()

 val gson = GsonBuilder()
            .setLenient()
            .create()

        return Retrofit.Builder()
            .baseUrl(...)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .client(okHttpClient)
            .build()
            .create(...)

标签: androidjsonkotlingsonretrofit

解决方案


推荐阅读