skip to content

HTTP Errors & Failures

Response<T> versus a thrown HttpException, parsing an error body, telling an IOException from an HTTP failure, and mapping each to a sealed result. Whether a 404 throws depends on the return type.

on this pageshow

explore

questions

5

With Retrofit, what happens on an HTTP 404 when a suspend service method returns User instead of Response<User>?

level: juniorimportance: must knowfreq 75%

answer

  1. what the declared return type promises
  2. who checks the status code
  3. HttpException carries the response
  4. isSuccessful covers 200 to 299
  5. transport failures throw either way

basics

~20 s

Returning User, the suspend method throws HttpException on a 404, since it can only hand back a body. Returning Response<User>, it returns normally and you check isSuccessful, code() and errorBody(); a network failure throws either way.

solid answer

~40 s

Retrofit treats any status outside 200 to 299 as unsuccessful, and the declared return type decides how that reaches you. A `suspend fun user(): User` can only return a body, so on a 404 Retrofit throws `retrofit2.HttpException`; `e.code()` is 404 and `e.response()?.errorBody()` holds the server's payload. A `suspend fun user(): Response<User>` returns normally: `isSuccessful` is false, `body()` is null and the payload sits in `errorBody()`. Neither form turns a transport problem into a response: a DNS failure, a timeout or a dropped connection is still thrown as an `IOException`, and a 2xx body the converter cannot read still throws. So `Response<T>` changes how HTTP errors arrive, not whether the caller needs error handling.

code

kotlin · 31 lines
kotlin
import retrofit2.HttpException
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Path

data class User(val id: Long, val name: String)

interface UserApi {
    @GET("users/{id}")
    suspend fun user(@Path("id") id: Long): User

    @GET("users/{id}")
    suspend fun userResponse(@Path("id") id: Long): Response<User>
}

suspend fun loadBoth(api: UserApi, id: Long) {
    try {
        val user = api.user(id)                 // a 404 throws here
        println(user)
    } catch (e: HttpException) {
        println("HTTP ${e.code()}")             // prints HTTP 404
    }

    val response = api.userResponse(id)         // a 404 returns normally
    if (response.isSuccessful) {
        println(response.body())
    } else {
        println("HTTP ${response.code()}: ${response.errorBody()?.string()}")
    }
    // An IOException from either call is not caught here and propagates.
}

go deeper

for a junior

Recall the rule: a body return type throws HttpException for any non-2xx status, while Response<User> returns and you check isSuccessful. Say where the error payload lives in each case.

for a middle

Explain that the status check happens before conversion: Retrofit buffers a non-2xx body into errorBody() and never runs the body converter on it, then the declaration decides whether that becomes an exception.

for a senior

Show you know Response<T> is not a safety net: transport failures and conversion failures still throw, so both declarations need an IOException catch and an unexpected-error path.

for a principal

Treat the return type as a team convention: it decides whether HTTP errors are values or exceptions across the data layer, and mixing both styles service by service makes failures easy to miss.

## Two declarations, one HTTP outcome Retrofit turns an interface method into an HTTP call. Since **Retrofit 2.6.0**, a Kotlin `suspend` method can return either the **body type** directly (`User`) or the **`Response<User>` wrapper**. Both send exactly the same request and receive exactly the same 404 from the server. What differs is the **contract the declaration promises the caller**, and that contract decides whether the 404 is thrown or returned. - **`suspend fun user(@Path("id") id: Long): User`** promises a `User`. When the server answers 404 there is no `User` to give back, so the method cannot return normally. - **`suspend fun user(@Path("id") id: Long): Response<User>`** promises a *response*. A 404 is a perfectly good response, so the method returns it and leaves the judgement to you. ## What Retrofit does with a non-2xx response Before any adapter or coroutine is involved, Retrofit's call implementation inspects the raw OkHttp response: 1. If the status code is **outside 200 to 299**, Retrofit reads the whole body into memory, closes the network stream and builds an error `Response` whose `body()` is null and whose `errorBody()` holds those bytes. The body converter is **never run** on an error. 2. If the status is **204 or 205**, it closes the body and builds a successful `Response` with a null body. 3. Otherwise it runs the registered converter and builds a successful `Response` with the converted body. `Response.isSuccessful` is true exactly when the code is in **[200..300)**. That means "unsuccessful" is not only 4xx and 5xx: any 3xx that reaches Retrofit (OkHttp follows ordinary redirects by default before Retrofit sees anything) is handled the same way. ## Declared as the body type: HttpException For a suspend method returning the body, Retrofit awaits that `Response` and then checks `isSuccessful`. If it is false, the coroutine resumes with **`retrofit2.HttpException`**, a `RuntimeException` whose message reads like `HTTP 404 ...` and which exposes: - **`code()`**: the status code, here 404. - **`message()`**: the HTTP status message the server sent. - **`response()`**: the full `Response`, so `e.response()?.errorBody()` gives the server's error payload. It is nullable because the response is not kept if the exception is serialized. The same rule applies to other adapters that deliver only a body: Retrofit's RxJava 3 adapter, for example, signals `HttpException` from an `Observable<User>`. ## Declared as Response<T>: you inspect it With `Response<User>` the coroutine resumes normally for every status. The caller writes the branch itself: - `response.isSuccessful` decides the path. - `response.body()` is the converted `User` on success and **null** on a 404. - `response.errorBody()` is the buffered error payload on a 404 and null on success. - `response.code()` and `response.headers()` are available in both cases. | Outcome | `suspend ...: User` | `suspend ...: Response<User>` | `Call<User>` with `enqueue` | |---|---|---|---| | 200 with a valid body | returns the `User` | returns a successful `Response` | `onResponse`, `isSuccessful()` true | | 404 with an error payload | throws `HttpException` | returns a `Response`, `isSuccessful` false | `onResponse`, `isSuccessful()` false | | DNS failure, timeout, reset | throws `IOException` | throws `IOException` | `onFailure` with the `IOException` | | 200 the converter cannot read | throws the converter's exception | throws the converter's exception | `onFailure` with that exception | ## What still throws either way The wrapper only covers outcomes where an HTTP response **arrived and was classified**. Two kinds of failure happen before or after that point and are thrown in both declarations: - **Transport failures**: no route to the host, a failed DNS lookup, a timeout, a connection dropped mid-body. OkHttp reports these as an `IOException` (for example `UnknownHostException` or `SocketTimeoutException`), and there is no status code to wrap. - **Conversion failures** on a 2xx: the converter could not turn the body into a `User`, so there is no body to put in the `Response`. A common interview slip is to say `Response<T>` "never throws". It never throws *for an HTTP status*; it still needs a `catch` for `IOException` and for unexpected exceptions. ## Choosing at the call site - Return the **body type** when a non-2xx is genuinely exceptional for that endpoint and a surrounding handler maps `HttpException` once. - Return **`Response<T>`** when the status, headers or error payload are part of normal flow, such as a 404 that means "not found, show an empty state". - With **`Call<T>`** and `enqueue`, remember that a 404 arrives in `onResponse`, not `onFailure`, and that on Android both callbacks run on the main thread by default.

  • With a Call<User> run through enqueue, which Retrofit callback receives a 404?
    `onResponse`, not `onFailure`. Retrofit delivers a non-2xx as a `Response` whose `isSuccessful()` is false, with the payload in `errorBody()`. `onFailure` receives throwables: an `IOException` from the transport, or an exception thrown while building the request or converting a successful body. On Android both callbacks run on the main thread by default.
  • Does Retrofit treat a 3xx response that reaches it as a success?
    No. `isSuccessful` is true only for 200 to 299. OkHttp follows ordinary redirects before Retrofit sees the response, but any 3xx that does reach Retrofit, such as a 304, is handled like an error: the body is buffered into `errorBody()` and a suspend method returning the body type throws `HttpException`.

Ordering by phone: ask for the parcel itself and a refusal reaches you as a problem the clerk throws back at you; ask for the delivery report and you always get a report to read, refusal included. If the phone line is dead, you get neither.

  • Returning Response<User> means the suspend call can never throw.
  • Retrofit only throws HttpException for 5xx errors, so a 404 returns null.
  • With Call.enqueue a 404 arrives in onFailure.
  • HttpException is an IOException, so one catch handles both.
  • On a 404, body() holds the parsed error payload.

Assumes Retrofit 3.0.0; suspend service methods, and the HttpException they throw for a non-2xx response, date from Retrofit 2.6.0.

open as a page

In a Retrofit checkout call, how do you tell no network, a declined card's HTTP 402 and a malformed response body apart?

level: middleimportance: must knowfreq 70%

basics

~20 s

No 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.

open as a page

With Retrofit, how do you parse the JSON error body of a failed call, such as a 402 card decline, into a typed object?

level: middleimportance: should knowfreq 60%

basics

~10 s

Ask 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.

open as a page

A Retrofit suspend method declared with a nullable Receipt return type throws KotlinNullPointerException on a 204 No Content; why, and what should it declare instead?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Retrofit returns a null body for 204 and 205, and its suspend support cannot see the ? in Receipt?, so it treats the type as non-null and throws KotlinNullPointerException. Declare Response<Receipt> and check body(), or Unit when no body ever comes.

open as a page

As Android lead, should your Retrofit data layer report outcomes as a thrown HttpException, Response<T> or a sealed result, and where should that mapping live?

level: principalimportance: should knowfreq 45%

basics

~20 s

Keep Retrofit's exceptions inside the data layer: map every call once into a sealed result with success, HTTP error with a parsed body, network failure and unexpected cases. Callers then handle failures exhaustively instead of remembering which exceptions to catch.

open as a page