In a Retrofit checkout call, how do you tell no network, a declined card's HTTP 402 and a malformed response body apart?
answer
- did a response arrive at all
- three different exception families
- transport problems surface as IOException
- non-2xx becomes HttpException, a RuntimeException
- the converter throws on a bad 2xx body
basics
~20 sNo network surfaces as an IOException. A 402 is a complete response, so a suspend method returning the body throws HttpException with code() 402. A malformed 2xx body fails in the converter, which throws its own exception.
solid answer
~40 sThey fail at three different points, so they reach the caller as three exception families. If no response arrives (no route, a failed DNS lookup, a timeout, a dropped connection), OkHttp reports an `IOException` such as `UnknownHostException` or `SocketTimeoutException`. If a response arrives with a status outside 200 to 299, Retrofit buffers its body into `errorBody()` and a suspend method returning the body type throws `HttpException`, a `RuntimeException` rather than an `IOException`; `e.code()` is 402 and the decline payload is in `e.response()?.errorBody()`. If a 2xx arrives but the converter cannot read it, the converter's own exception propagates. One caveat: `Converter.convert` is declared `throws IOException`, so an `IOException` is strong evidence of a transport failure but not proof of one.
code
kotlin · 37 linesimport java.io.IOException
import kotlin.coroutines.cancellation.CancellationException
import retrofit2.HttpException
import retrofit2.http.Body
import retrofit2.http.POST
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): Receipt
}
sealed interface CheckoutOutcome {
data class Paid(val receipt: Receipt) : CheckoutOutcome
data class Declined(val payload: String?) : CheckoutOutcome
data object Offline : CheckoutOutcome
data class Broken(val cause: Throwable) : CheckoutOutcome
}
suspend fun pay(api: PaymentsApi, request: ChargeRequest): CheckoutOutcome =
try {
CheckoutOutcome.Paid(api.charge(request))
} catch (e: CancellationException) {
throw e
} catch (e: HttpException) {
if (e.code() == 402) {
CheckoutOutcome.Declined(e.response()?.errorBody()?.string())
} else {
CheckoutOutcome.Broken(e)
}
} catch (e: IOException) {
CheckoutOutcome.Offline
} catch (e: RuntimeException) {
CheckoutOutcome.Broken(e)
}go deeper
Know the two names: IOException means no usable response arrived, HttpException means the server answered with a status outside 200 to 299.
Walk through where each failure happens in a Retrofit call (transport, status check, conversion) and why HttpException is a RuntimeException that an IOException catch never sees.
Show the production edges: a converter allowed to throw IOException, a mid-body disconnect rethrown as the original IOException, and a broad catch that must let coroutine cancellation through.
Treat the three families as different product signals: offline earns a retry, a decline shows the server's reason, and a conversion failure is a contract bug that belongs in crash reporting.
## Three failures, three places they happen A checkout screen has to tell three situations apart, because each needs a different response from the app: **no network** (offer a retry), **a declined card** (show the server's reason) and **a malformed response** (a bug; the user can do nothing about it). With Retrofit, the three are easy to separate once you know *where in the call* each one happens: 1. **Sending and receiving bytes.** OkHttp opens a connection, writes the request and reads the response. Failure here means no usable response exists. 2. **Classifying the status.** Retrofit looks at the status code of the response that did arrive. 3. **Converting the body.** For a 2xx, Retrofit runs the registered converter (Gson, Moshi, kotlinx.serialization or another) to build the declared type. Each stage normally reports failure with a different type, and a suspend method that returns the body (`suspend fun charge(@Body r: ChargeRequest): Receipt`) throws whichever applies. ## No response at all: IOException When the device is offline, the host cannot be resolved, the connection is refused, a timeout fires or the socket drops, **OkHttp throws an `IOException`**. Typical subclasses are `UnknownHostException`, `ConnectException` and `SocketTimeoutException`. There is no status code because the server never answered, or its answer never arrived whole. A subtle case: the connection dies **halfway through a 2xx body** while the converter is reading it. JSON libraries sometimes wrap a read error in their own runtime exception. Retrofit guards against that: it hands the converter a wrapped body that records any `IOException` thrown by the underlying source, and if conversion then fails with a `RuntimeException`, Retrofit **rethrows the recorded `IOException`** instead. So a mid-body disconnect is still reported as a transport failure. ## A response with a non-2xx status: HttpException A declined card answered with **HTTP 402** and a JSON body is a *complete, successful exchange* at the transport level. Retrofit: - reads the error body fully into memory and closes the stream; - does **not** run the body converter on it; - throws **`retrofit2.HttpException`** from the suspend method, because there is no `Receipt` to return. `HttpException` extends **`RuntimeException`**, not `IOException`. A `catch (e: IOException)` block never sees it. Read `e.code()` for the status and `e.response()?.errorBody()` for the payload (turning that payload into a typed object is its own step, done with a converter from the Retrofit instance). ## A 2xx that cannot be read: the converter's exception If the server answers 200 but the body is not what the declared type expects (truncated JSON, an HTML page from a proxy, a missing field the library refuses to default), the converter throws and the suspend method rethrows it unchanged. Which class you get depends on the library, and the `Converter.convert` contract is declared **`throws IOException`**, so a converter is allowed to report bad input as an `IOException` too. Treat an `IOException` as very likely a transport failure, not as proof. | Situation | Where it fails | What the suspend method throws | What the user should see | |---|---|---|---| | Offline, DNS failure, timeout | transport | `IOException` | retry or offline message | | Card declined, HTTP 402 | status check | `HttpException`, `code()` 402 | the server's decline reason | | 200 with a body the converter rejects | conversion | the converter's exception | a generic error; log it as a bug | ## Putting the catches in order - Catch **`HttpException`** and **`IOException`** separately; they are unrelated types, so their relative order does not matter. - Put any broad `catch (e: RuntimeException)` or `catch (e: Exception)` **last**, so it only collects what the specific branches did not. - A broad catch inside a coroutine must let **`CancellationException`** through, or a screen that leaves mid-call turns cancellation into a fake failure (coroutine cancellation itself is covered in the lessons on Kotlin coroutines). - Reading `e.response()?.errorBody()` costs no network I/O: Retrofit already buffered it. ## With Response<T> or Call instead Declaring `Response<Receipt>` moves the 402 out of the exception path: the method returns, `isSuccessful` is false and `errorBody()` holds the payload. The transport `IOException` and the converter's exception are **still thrown**. With `Call<Receipt>` and `enqueue`, the 402 arrives in `onResponse`, and both the `IOException` and a conversion exception arrive in `onFailure`, so you still check the throwable's type there.
- Why can a connection dropped halfway through a 200 body still arrive as an IOException rather than a JSON parsing error?Retrofit gives the converter a wrapped body that records any `IOException` the socket throws while being read. If the converter wraps that in its own `RuntimeException`, Retrofit checks the record and rethrows the original `IOException` instead, so a mid-body disconnect is reported as a transport failure, not as malformed data.
- Where do these three failures arrive when the method returns Call<Receipt> and you use enqueue?The 402 arrives in `onResponse` with `isSuccessful()` false and the payload in `errorBody()`. The transport `IOException` and the converter's exception both arrive in `onFailure`, so inside `onFailure` you still check whether the throwable is an `IOException` to separate no network from a body Retrofit could not convert.
- HttpException extends IOException, so catching IOException also handles the 402.
- Retrofit runs the JSON converter on the 402 body and throws when it fails.
- A malformed 200 body is reported as an HttpException.
- Every IOException proves the device is offline.
- Catch Exception once and show the same connection message for every failure.