有没有办法在onError分支中获取数据模型?

时间:2019-02-13 12:18:18

标签: android kotlin retrofit rx-java2

我正在通过Retrofit和RXJava从API获取数据模型。模型包含带有自定义消息的错误字符串。

{"data":[],"errors":[{"code":168,"message":"Number is out of bounds"}]}

订阅功能:

subscribe({
       eventLiveData.value = SubmitFinished
    }, { // it: Throwable!
       eventLiveData.value = SubmitResponseError
       // I want to have my object here!
    })

有什么办法可以让我的对象在onError分支中带有错误代码? 谢谢

1 个答案:

答案 0 :(得分:2)

是的,onError得到Throwable对象,可以将其投射到HttpException

data class Data(
    @SerializedName("content") val content: String
)

data class Error(
    @SerializedName("code") val code: Int,
    @SerializedName("message") val message: String,
)

data class Response(
    @SerializedName("data") val data: List<Data>,
    @SerializedName("errors") val errors: List<Error>
)

fun onError(e: Throwable): List<Error>? {
    return try {
        val httpException = e as? HttpException
        val errors = JSONObject(httpException?.response()?.errorBody()?.string()).get("errors") as List<Error>
    } catch (ignore: Exception) {
        null
    }
}

查看本文:

https://medium.com/mindorks/rxjava2-and-retrofit2-error-handling-on-a-single-place-8daf720d42d6