使用 RxJava 改造 - 自定义故障数据 class

Retrofit with RxJava - custom failure data class

我有一个 API 向我发送自定义错误 JSON 低于 500 错误

所以,这是我的 Api 界面:

  @POST("${API_PREFIX}method")
  fun callForIt(@Body request: MyRequest) : Single<MyResponse>

我是这样称呼它的:

api.callForIt(request)
   .observeOn(AndroidSchedulers.mainThread())
   .subscribe(
     {
      // Here I get perfect MyResponse object
     },
     {
      // And here I get only throwable, but need to get info from the json
     })

所以,我想要的是描述自定义数据 class,例如

data class ErrorResponse(
  val type: String,
  val fatal: Boolean,
  val msg: String
// etc
)

因为服务器正在 JSON 中向我发送有价值的信息,我需要获取它,所以有什么方法可以从 onFailure()?

中读取它
{ t: Throwable ->
    if (t is HttpException) {
        val errorMsg = t.response()!!.errorBody()!!.string()
        val errorResponse = Gson().fromJson(errorMsg, ErrorResponse::class)
        // handle the error with errorResponse...
    }
    else {
        // handle the error with code >=500...
    }
}