【问题标题】:Is there way to get data model in onError branch?有没有办法在 onError 分支中获取数据模型?
【发布时间】:2019-07-07 06:39:57
【问题描述】:

我通过 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 分支中有错误代码? 谢谢

【问题讨论】:

    标签: android kotlin retrofit rx-java2


    【解决方案1】:

    是的,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

    【讨论】:

    • 发布与问题相关的实际部分而不是链接会更合适。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 2022-11-18
    • 2012-08-13
    • 1970-01-01
    • 2017-05-27
    • 2011-07-20
    相关资源
    最近更新 更多