Retrofit 2.0 how to get deserialised error response.body

前端 未结 21 2260
庸人自扰
庸人自扰 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:09

    If you use Kotlin another solution could be just create extension function for Response class:

    inline fun Response<*>.parseErrJsonResponse(): T?
    {
        val moshi = MyCustomMoshiBuilder().build()
        val parser = moshi.adapter(T::class.java)
        val response = errorBody()?.string()
        if(response != null)
            try {
                return parser.fromJson(response)
            } catch(e: JsonDataException) {
                e.printStackTrace()
            }
        return null
    }
    

    Usage

    val myError = response.parseErrJsonResponse()
    if(myError != null) {
       // handle your error logic here
       // ...
    }
    

提交回复
热议问题