skip to content

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%

answer

  1. who has to remember to catch
  2. exceptions or values at the boundary
  3. one mapper beside the Retrofit instance
  4. domain cases for expected HTTP errors
  5. a conversion failure is a bug signal

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.

solid answer

~40 s

There is no single right answer, but I would keep Retrofit types from crossing the data layer. Throwing suspend methods are the simplest to declare, yet every caller must remember `HttpException` and `IOException`, and one forgotten catch crashes a screen. `Response<T>` turns HTTP errors into values but still throws for transport and conversion failures, and spreads `errorBody()` handling across call sites. So I would standardise on a sealed result (success, HTTP error with the parsed body, network failure, unexpected) produced in one place: a small wrapper around service calls, or a custom call adapter if the team wants service methods to return the result directly. Repositories then turn expected HTTP errors such as a 402 decline into domain cases, conversion failures go to crash reporting, and coroutine cancellation is always rethrown.

code

kotlin · 29 lines
kotlin
import java.io.IOException
import kotlin.coroutines.cancellation.CancellationException
import retrofit2.HttpException
import retrofit2.Response

data class ApiError(val code: String, val message: String)

sealed interface ApiResult<out T> {
    data class Success<T>(val value: T) : ApiResult<T>
    data class HttpError(val code: Int, val error: ApiError?) : ApiResult<Nothing>
    data class NetworkError(val cause: IOException) : ApiResult<Nothing>
    data class UnexpectedError(val cause: Throwable) : ApiResult<Nothing>
}

// parseError wraps retrofit.responseBodyConverter for ApiError and reads errorBody() once.
class ApiCaller(private val parseError: (Response<*>) -> ApiError?) {
    suspend fun <T> call(block: suspend () -> T): ApiResult<T> =
        try {
            ApiResult.Success(block())
        } catch (e: CancellationException) {
            throw e
        } catch (e: HttpException) {
            ApiResult.HttpError(e.code(), e.response()?.let(parseError))
        } catch (e: IOException) {
            ApiResult.NetworkError(e)
        } catch (e: RuntimeException) {
            ApiResult.UnexpectedError(e)
        }
}

go deeper

for a junior

Know the three ways a Retrofit failure can reach your code: a thrown HttpException, a Response you inspect, or a result value, and that the team picks one.

for a middle

Explain what each style forces a caller to write and which failure each lets a caller forget, naming IOException and HttpException.

for a senior

Show you can build the shared mapper: explicit catches, cancellation rethrown, the error body parsed once, and the original cause kept for logging.

for a principal

Weigh declaration simplicity against safety for the whole codebase: where Retrofit types stop, which HTTP errors become domain cases, how review enforces it, and when a small app should not bother.

## The decision Every Retrofit call that completes ends in one of four outcomes: a **success**, an **HTTP error** (a status outside 200 to 299, with an error body), a **network failure** (an `IOException`, no usable response) or something **unexpected** (a converter that could not read a 2xx body, a null body on a non-null declaration). A codebase with dozens of endpoints needs one answer to a question a lead owns: *in what form do those outcomes reach the code above the data layer?* There is no universally right answer; the choice trades declaration simplicity against how easy it is for a caller to forget a failure. ## The three options compared | Option | What a caller writes | What a caller can forget | Main cost | |---|---|---|---| | Suspend methods return the body; failures throw | `try` with `HttpException`, `IOException` and a fallback | any catch, so a screen crashes on a 402 or offline | failures are invisible in signatures | | Suspend methods return `Response<T>` | an `isSuccessful` branch plus a `try` for `IOException` | the `try`, since transport and conversion still throw | `errorBody()` parsing repeated at call sites | | A sealed result type | an exhaustive `when` over the cases | nothing the compiler does not flag | one shared mapper to write and maintain | The first two are honest about Retrofit's mechanics but leak them: `HttpException`, `Response` and `errorBody()` end up in view models. The third pays a small, one-time cost to make every failure a value the compiler forces callers to handle. ## What the sealed result should carry - **`Success(value)`**: the converted body. - **`HttpError(code, error)`**: the status plus the error body **parsed once** with a converter from the Retrofit instance (`retrofit.responseBodyConverter`), nullable when the payload is not the agreed shape. - **`NetworkError(cause: IOException)`**: offline, DNS failure, timeout, a dropped connection. - **`UnexpectedError(cause: Throwable)`**: everything else, chiefly conversion failures and a null body on a non-null declaration. Keep the case list short: four generic cases, plus domain cases added by the repositories that need them, is enough for most apps. Keep the **original exception** in each failure case. Throwing it away makes the crash report for a contract bug say nothing useful. ## Where the mapping lives 1. **A wrapper function in the data layer**, such as `suspend fun <T> call(block: suspend () -> T): ApiResult<T>`, used by every repository. It is visible at each call site, trivial to unit-test and easy for newcomers to read. 2. **A custom call adapter**, so service methods declare `ApiResult<T>` directly and no call can skip the mapping. The cost is owning adapter code and a non-standard declaration style (how such an adapter is built is covered with Retrofit's call adapters). 3. **Repositories translate to domain cases.** A 402 with `card_declined` becomes `CheckoutResult.Declined(message)`; a 409 becomes a conflict the user resolves. Codes nobody plans for stay generic and get logged with their status. ## Rules the team enforces - **Cancellation is never a failure.** The wrapper rethrows `CancellationException`; Kotlin's `runCatching` catches every `Throwable`, cancellation included, which is one reason not to build the result with it (cancellation itself is covered in the lessons on Kotlin coroutines). - **Conversion failures are bugs, not connectivity.** They map to `UnexpectedError`, reach crash reporting, and never show the user an offline message. - **One error parser.** Built once beside the Retrofit instance, reading the error body exactly once. - **Retrofit types stop at the repository.** Review rejects `HttpException`, `Response` or `errorBody()` in a view model. - **Tests use synthetic responses.** `Response.error(402, body)` and a fake service cover every case without a server. ## When not to wrap A lead also decides when the abstraction is not worth it: - a small app or prototype with a handful of endpoints, where a shared `try` block is clearer; - a streaming download whose progress and partial failure need their own model; - an existing RxJava 3 stack that already standardises on Retrofit's `Result` wrapper, where a second result type would only add a translation layer. Whatever is chosen, write it down once and apply it to every service: two conventions in one codebase is how a 402 ends up crashing one screen and showing a toast on another.

  • Why not build the Retrofit result with Kotlin's runCatching?
    `runCatching` catches every `Throwable`, including the `CancellationException` a cancelled coroutine uses to unwind, so a screen leaving mid-call becomes a fake failure, and fatal errors are captured too. It also yields an untyped failure, so callers are back to checking exception classes. Explicit catches keep cancellation propagating and the cases exhaustive.
  • When is a custom call adapter better than a wrapper function for producing the sealed result?
    When the team wants service methods to declare the result type directly, so no call can bypass the mapping. The cost is owning adapter code that every new return type passes through and a declaration style newcomers must learn. A wrapper function stays visible at each call site and is easier to test.
  • Which HTTP errors deserve their own domain cases rather than a generic HttpError?
    The ones the product handles as normal outcomes: a 402 card decline, a 409 conflict the user resolves, a 422 validation error with field messages. The repository maps those, with the parsed error body, into cases the screen renders. Unplanned codes stay generic and are logged with their status, so the sealed type does not grow a case per status code.

  • Returning Response<T> everywhere means callers never need a try/catch.
  • A conversion failure should be shown to the user as a connectivity problem.
  • Catching Throwable in the wrapper is safest because nothing can escape.
  • Each screen should parse errorBody() itself to show its own message.
  • A sealed result needs one case for every HTTP status code.