如何使用GsonConverter处理全局解析错误



我正在使用RxJava,改装,GsonConverter工厂。我需要在全局解析改装响应时处理错误。我试图编写自定义解析器,但无法访问响应url将其传递给我的分析服务。有什么可行的方法可以正确地实现吗

class GsonResponseBodyConverter<T>(
private val gson: Gson,
private val adapter: TypeAdapter<T>,
private val analytics: Analytics
) : Converter<ResponseBody, T> {
private val errorResponseSubject = PublishSubject.create<Pair<Throwable, String>>()
init {
val errorResponseFlowable = errorResponseSubject.toFlowable(BackpressureStrategy.BUFFER)
val disposable = Flowables.combineLatest(
errorResponseFlowable,          
Mapper::exceptionToEntity
)
.flatMap { analytics.saveError(it).andThen(Flowable.just(Unit)) }
.subscribeOn(Schedulers.IO)
.subscribe({ /* no-op */
print(it)
}, RxThrowable.printStackTrace(logger))
}
@Throws(IOException::class)
override fun convert(value: ResponseBody): T {
val jsonReader = gson.newJsonReader(value.charStream())
return value.use {
runCatching {
val result = adapter.read(jsonReader)
if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
throw JsonIOException("JSON document was not fully consumed.")
}
result
}.getOrElse { error ->
errorResponseSubject.onNext(Pair(error, URL - I don't have access to url here!))
throw error
}
}
}
} 

使用转换器和调用适配器混合解决了我的问题(https://github.com/square/retrofit/issues/2267/

相关内容

  • 没有找到相关文章

最新更新