Hi,
Recently I was assigned to get a response error object using retrofit. Although there were some artciles and SO questions regard to this, I hardly find a usage of Kotlin, Retrofit and Moshi combination. Therefore I am writing this blog how to use this combination.
(I'm showing my actual working code here and the code should be self-explanatory. I am putting notes under every code snippet where necessary and explain a bit more)
So this is the response which I get when something goes wrong.
Here is the error response class which is reusable.
@JsonClass(generateAdapter = true)
data class BaseResponse<T>(
@Json(name = "statusCode") val statusCode: Int,
@Json(name = "result") val result: T? = null,
@Json(name = "errorCode") val errorCode: String? = null
)
Here is the JsonParser class which is responsible for json converting.
class JsonParser {
fun moshi() = Moshi.Builder().build()
inline fun <reified T> toBaseResponseError(json: BufferedSource): BaseResponse<T>? {
return BaseResponseJsonAdapter<T>(moshi(), arrayOf(T::class.java)).fromJson(json)
}
// other json converters
}
Here is how to use that error response converter object.
Service(this, Utils().getAccessToken(this)).getUser(
object : retrofit2.Callback<BaseResponse<HealthPersonInfo>> {
override fun onFailure(call: Call<BaseResponse<HealthPersonInfo>>, t: Throwable) {
hideProgress()
}
override fun onResponse(
call: Call<BaseResponse<HealthPersonInfo>>,
response: Response<BaseResponse<HealthPersonInfo>>
) {
hideProgress()
if (response.isSuccessful) {
response.body()?.let {
// do what you need when the call is success
}
} else {
response.errorBody()?.let {
val errorResponse = JsonParser().toBaseResponseError<HealthPersonInfo>(it.source())
// now you have an error object(errorResponse ) and you can use it's properties as follows
val code = errorResponse?.errorCode
}
}
}
})
Note : The "Service" class is responsible for creating retrofit builder. It has methods like "getUser" which constructs get user url and callback. "HealthPersonInfo" is a class which is used when we have a successful return.
Hope you can get something helpful. Happy coding!!!
No comments:
Post a Comment