改造+协同程序:使用Gson进行自定义错误处理

时间:2019-08-09 15:47:16

标签: android kotlin gson retrofit

我在API调用上使用带有suspend的Retrofit v2.6.1。

interface Service {
    @POST("/login")
    suspend fun login(): User
}

我的API发送需要Gson解析的自定义错误响应

{
    "message": "Credentials given does not identify a user or cannot be used to authenticate a user.",
    "error_code": "BAD_CREDENTIALS",
    "error_code_description": "Credentials given does not identify a user or cannot be used to authenticate a user.",
    "correlation_id": "api-fYXbwOaPzOjJ"
}

如何与协程一起定制这些错误响应的处理方式?

我应该使用转换器吗? TypeAdapters?反序列化器?

2 个答案:

答案 0 :(得分:0)

您可以创建一个所有模型都继承自的基本Error类,像这样

open class Error {
    val message: String? = null
    val error_code: String? = null
    val error_code_description: String? = null
    val correlation_id: String? = null
}

data class User(
        val name: String
) : Error()

您还可以将方法添加到基类中,以确定是否出错

open class Error {
    val message: String? = null
    val error_code: String? = null
    val error_code_description: String? = null
    val correlation_id: String? = null

    fun isErrorResponse() : Boolean = error_code != null
}

答案 1 :(得分:0)

如果您的API总是返回相同的模板,则可以创建一个可序列化的类,并让GSON处理反序列化。

适合您的情况的示例类是

data class ErrorItem(
    @SerializedName("message")
    val message: String? = null,

    @SerializedName("error_code")
    val message: String? = null,

    @SerializedName("error_code_description")
    val message: String? = null,

    @SerializedName("correlation_id")
    val message: String? = null,
)

看看反序列化器https://discuss.kotlinlang.org/t/retrofit-an-gson-deserialize-a-specific-object-type-based-on-the-value-of-a-field/10440/4