Reputation: 2027
I'm using Retrofit2 in an Android app. Here's my response code:
override fun onResponse(call: Call<Asset>?, response: Response<Asset>?) {
val errorStart = response?.errorBody()?.string() // I get "ERROR" here
if (response != null && response.isSuccessful) {
// A successful response was returned
completion(response.body(), null)
} else {
// Not success
val errorElse = response?.errorBody()?.string() // I get "" here
val error = Error(errorText)
completion(null,error)
}
}
and here's the code I'm using to test my code:
response = Response.Builder()
.code(403)
.message(responseString)
.request(chain.request())
.protocol(Protocol.HTTP_1_0)
.body(ResponseBody.create(MediaType.parse("application/json"), "ERROR"))
.addHeader("content-type", "application/json")
.build()
When the code run and a response is returned response?.errorBody()?.string()
is a string and I can capture it, as I have in this code as val errorStart.
...But...
when I run the IF code/logic and attempt to capture response?.errorBody()?.string()
in the else code block it's now blank/gone.
Can someone explain what's going on or what I'm doing wrong? What is the proper way to capture error information in OnResponse?
Upvotes: 0
Views: 313