android - 如果发生 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(...)
解决方案
推荐阅读
- c# - 识别 USB 集线器上设备的端口号
- html - 使用管道的角度过滤器帖子
- python - 如何使用 python 获取我的 youtube 历史中最后观看的视频?
- wso2 - 在 WSO2 IS 5.10 中进行后端 api 调用时出现 CORS 问题的示例 Pickup 调度 Web 应用程序
- mysql - 如何从 MariaDB/MySQL 中的日期时间获取一分钟的开始?
- java - JavaFX 2D 组合框
- javascript - Javascript 运行代码显示为空
- typescript - typescript interfacer type between two values
- html - 将固定宽度设置为父级的 100% 高度
- r - how to use mutate c_across when there's multiple "." arguments in the same line