How do I get Response body when there is an error when using Retrofit 2.0 Observables

前端 未结 3 1740
眼角桃花
眼角桃花 2021-01-31 16:13

I am using Retrofit 2.0 to make api calls that return Observables. It all works good when the call went through fine and the response is as expected. Now let\'s say we have an e

3条回答
  •  故里飘歌
    2021-01-31 16:32

    Retrofit returns the Throwable Object which is a type of HttpException. First Step that you need to do is that you should know the structure of you error body object. Will show how to do it Kotlin. Once you know the structure, you need to create Error.kt file like shown below :

    package com.test.test.qr.data.network.responsemodel
    import com.google.gson.annotations.SerializedName
    
    data class Error(
        @SerializedName("code")
        val code: String,
        @SerializedName("message")
        val message: String
    )
    

    Now you need to parse the body from HttpException to Error.Kt you created. This can be done as shown below :

    if(it is HttpException) {
        val body = it.response()?.errorBody()
        val gson = Gson()
        val adapter: TypeAdapter = gson.getAdapter(Error::class.java)
        try {
            val error: Error = adapter.fromJson(body?.string())
            Log.d("test", " code = " + error.code + " message = " + error.message)
        } catch (e: IOException) {
           Log.d("test", " Error in parsing")
        }
    }
    

    Where it is the Throwable you get in onError() from retrofit. Hope it helps. Happy Coding...:-)

提交回复
热议问题