With Retrofit, how do you parse the JSON error body of a failed call, such as a 402 card decline, into a typed object?
answer
- the body converter never ran
- reuse the Retrofit instance's converters
- responseBodyConverter for the error type
- errorBody() is consumed by one read
- HttpException.response() can be null
basics
~10 sAsk the Retrofit instance for a converter with retrofit.responseBodyConverter(ApiError::class.java, emptyArray()) and run it on errorBody(). The first read consumes the error body, so parse it once and keep the result.
solid answer
~40 sRetrofit never runs your body converter on a non-2xx response; it buffers the raw bytes and exposes them as `errorBody()` on the `Response`, or through `HttpException.response()` when a suspend method threw. To get a typed object, ask the same `Retrofit` instance for a converter for the error type, `retrofit.responseBodyConverter<ApiError>(ApiError::class.java, emptyArray())`, and call `convert(errorBody)`. That reuses the converter factories you registered, so error JSON is read with the same configuration as successful bodies. Build the converter once, wrap `convert` in a try/catch because a gateway may answer with HTML, and remember the first read consumes the body: log the parsed object, not a second `string()` call.
code
kotlin · 43 linesimport java.io.IOException
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.http.Body
import retrofit2.http.POST
data class ApiError(val code: String, val message: String)
data class ChargeRequest(val cartId: String, val cardToken: String)
data class Receipt(val id: String, val total: Long)
interface PaymentsApi {
@POST("charges")
suspend fun charge(@Body request: ChargeRequest): Response<Receipt>
}
class ApiErrorParser(retrofit: Retrofit) {
private val converter: Converter<ResponseBody, ApiError> =
retrofit.responseBodyConverter(ApiError::class.java, emptyArray<Annotation>())
fun parse(response: Response<*>): ApiError? {
val body = response.errorBody() ?: return null
return try {
converter.convert(body) // the one and only read of the error body
} catch (e: IOException) {
null
} catch (e: RuntimeException) {
null
}
}
}
suspend fun checkout(api: PaymentsApi, parser: ApiErrorParser, request: ChargeRequest): String {
val response = api.charge(request)
if (response.isSuccessful) return "paid"
val error = parser.parse(response)
return if (response.code() == 402 && error != null && error.code == "card_declined") {
error.message
} else {
"failed with HTTP ${response.code()}"
}
}go deeper
Recall that a failed Retrofit call keeps the server's payload in errorBody(), not body(), and that you parse it yourself.
Explain responseBodyConverter: the Retrofit instance hands you the converter its registered factories would use for the error type, so success and error JSON share one configuration.
Show the traps you have debugged: a body drained by a log line, a gateway's HTML that is not JSON, and HttpException.response() being null after serialization.
Decide where error parsing lives for the whole app, one parser beside the Retrofit instance and one error shape agreed with the backend, so screens never touch raw bodies.
## Why the error body is not already parsed A service method declares one body type, say `Receipt`, and Retrofit picks a converter for that type when it builds the method. A declined payment answered with **HTTP 402** carries a different shape, for example `{"code":"card_declined","message":"Insufficient funds"}`. Retrofit has no way to know that shape, so for any status outside 200 to 299 it does something deliberately simple: 1. It reads the **entire error body into memory** and closes the network stream. 2. It builds an unsuccessful `Response` whose `body()` is null and whose **`errorBody()`** returns those buffered bytes as an OkHttp `ResponseBody`. 3. It **never runs the body converter** on the error. Two consequences follow. Reading `errorBody()` performs **no network I/O**, because the bytes are already in memory. And leaving it unread **does not leak a connection**, because Retrofit already closed the underlying stream. ## Getting a converter from the Retrofit instance The clean way to parse the payload is to reuse the converter machinery Retrofit already has. `Retrofit.responseBodyConverter(Type, Annotation[])` returns a `Converter<ResponseBody, T>` from the first registered factory that can handle the type (factory order itself is covered with Retrofit's converters): - Call it **once**, for example in a small parser class built beside the `Retrofit` instance, and keep the converter. - Pass the error class as the `Type` and an empty annotation array. - Call **`convert(errorBody)`**; it returns the typed object. - If no registered factory can handle the type, the lookup throws `IllegalArgumentException` with "Could not locate ResponseBody converter for ...". Because the converter comes from the same factories as successful bodies, naming policies, lenient settings and Kotlin support are shared. The error class has to be something that converter can read, for instance annotated `@Serializable` when the instance uses the kotlinx.serialization converter. ## Reading it once OkHttp documents its `ResponseBody` as **consumable only once**. Retrofit's buffered error body behaves the same way in practice: the first `string()`, `bytes()` or `convert` drains the in-memory buffer, and a **second read finds nothing left**: `string()` returns an empty string and a converter fails on the empty input. The classic bug looks like this: - a log line calls `response.errorBody()?.string()` to print the payload; - the parser then calls `convert` on the same `errorBody()`; - the converter sees empty input and throws, so the typed error comes back null. Fix it by reading once: parse, then log the parsed object, or read the string once and keep it. ## Where the error body comes from | Declaration | Where a 402's payload lives | |---|---| | `suspend fun charge(...): Response<Receipt>` | `response.errorBody()` after `isSuccessful` is false | | `suspend fun charge(...): Receipt` | `(e as HttpException).response()?.errorBody()` | | `Call<Receipt>` with `enqueue` | `response.errorBody()` inside `onResponse` | `HttpException.response()` is **nullable**: the response is not kept when the exception is serialized, so handle null rather than asserting. ## Parsing after a thrown HttpException When the service method returns the body type, the same parser works from the catch block: `e.response()?.let(parser::parse)`. Three details make this safe: - the `Response` inside the exception is the one Retrofit built, so its `errorBody()` is the same buffered payload; - the parse is a read from memory, so it is cheap enough to run wherever the catch runs, main thread included; - a null `response()` simply yields a null error, and the status from `e.code()` is still available for a fallback message. ## When the parse itself fails The parse is a second, independent step that can fail on its own: - a **proxy or gateway** answers 502 with an HTML page, not JSON; - the server returns an **empty body** with the error status; - different endpoints use **different error shapes**; - the converter throws an `IOException` or a `RuntimeException`, depending on the library. Wrap `convert` in a try/catch that returns null (or a fallback object holding the status code), so a malformed error never hides the original failure. ## Testing the path `Response.error(402, body)` builds a synthetic error response without a server; it rejects codes below 400. Create the body from a JSON string with OkHttp's `toResponseBody` extension (OkHttp 4 and later) and feed it to the parser, or return it from a fake service, then assert both the code and the typed error.
- Why does logging errorBody()?.string() before parsing make the typed Retrofit error come back null?Retrofit buffers the error body in memory, and OkHttp's `ResponseBody` is consumed by its first read. The logging call drains the buffer, so the converter then reads an empty body, throws, and the try/catch returns null. Read the body once: parse it, then log the parsed object or a string you kept.
- How do you unit-test the 402 decline path without a running server?Build a synthetic failure with `Response.error(402, body)`, creating the body from a JSON string with OkHttp's `toResponseBody` extension. `Response.error` rejects codes below 400. Pass it to the parser, or return it from a fake service, and assert both `code()` and the typed `ApiError`.
- What happens if no registered converter factory can handle ApiError?`responseBodyConverter` throws `IllegalArgumentException` with a message starting "Could not locate ResponseBody converter for" and listing the factories it tried. Building the parser eagerly, at startup or in a test, surfaces that misconfiguration before a real decline does.
- Add the error fields to Receipt so the converter fills them on a 402.
- Call errorBody()?.string() as often as needed; Retrofit keeps a copy.
- An unread errorBody() leaks the HTTP connection.
- Parsing an error body needs a separately configured JSON instance.
- HttpException.response() is always non-null, so asserting it is safe.