Retrofit 2.0 how to get deserialised error response.body

前端 未结 21 2281
庸人自扰
庸人自扰 2020-11-28 02:46

I\'m using Retrofit 2.0.0-beta1.

In tests i have an alternate scenario and expect error HTTP 400

I would like to have retrofit.Respons

21条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 03:27

    Here is elegant solution using Kotlin extensions:

    data class ApiError(val code: Int, val message: String?) {
        companion object {
            val EMPTY_API_ERROR = ApiError(-1, null)
        }
    }
    
    fun Throwable.getApiError(): ApiError? {
        if (this is HttpException) {
            try {
                val errorJsonString = this.response()?.errorBody()?.string()
                return Gson().fromJson(errorJsonString, ApiError::class.java)
            } catch (exception: Exception) {
                // Ignore
            }
        }
        return EMPTY_API_ERROR
    }
    

    and usage:

    showError(retrofitThrowable.getApiError()?.message)

提交回复
热议问题