Retrofit error handling in Kotlin is one of those things every Android developer thinks they've solved until a user on a train loses signal mid-request and the app shows a raw UnknownHostException in a toast. I've been building Android apps for more than eight years, first as a Senior Android Engineer at CodeBrew Labs and now as a Senior Software Engineer at Raybit Technologies, and the network layer is still where I see the most fragile code in projects I inherit. In this post I'll walk through the exact pattern I use: typed errors, one wrapper for every call, proper error-body parsing, and clean mapping to UI state.

This isn't a theoretical exercise. When a freelance client asks me to stabilize an existing app, the network layer is usually the first place I look, because it touches every screen.

Why Most Android Apps Get Network Errors Wrong

Retrofit with suspend functions is deceptively simple. You declare suspend fun getProfile(): Profile, call it from a ViewModel, and it works. The problem is everything that happens when it doesn't work. A suspend Retrofit function can throw several very different things:

  • HttpException for any non-2xx response, like a 401, 404, 422 or 500.
  • IOException and its subclasses for connectivity problems: no network, DNS failure, connection reset.
  • SocketTimeoutException, which is technically an IOException but deserves its own treatment.
  • SerializationException (or a Gson/Moshi equivalent) when the backend returns JSON that doesn't match your model.
  • CancellationException when the coroutine scope is cancelled, for example when the user leaves the screen.

In code reviews I keep seeing the same patterns: a bare try/catch (e: Exception) in every ViewModel, error messages built from e.message, and no distinction between "you're offline" and "the server rejected your input." Users can't act on any of that. Worse, catching Exception blindly swallows cancellation, which quietly breaks structured concurrency.

The fix isn't a library. It's a small amount of deliberate architecture.

Modeling Retrofit Error Handling With Sealed Types

The first step is to stop letting exceptions leak past your data layer. Repositories should return a value that describes success or a specific, known failure. Kotlin's sealed interfaces are perfect for this because the compiler forces every when to handle every case.

sealed interface ApiResult<out T> {
    data class Success<T>(val data: T) : ApiResult<T>

    sealed interface Failure : ApiResult<Nothing> {
        data class Http(val code: Int, val error: ApiError?) : Failure
        data object Network : Failure
        data object Timeout : Failure
        data class Serialization(val cause: Throwable) : Failure
        data class Unknown(val cause: Throwable) : Failure
    }
}

A few deliberate choices here:

  • Failure is its own sealed interface. That lets UI mapping functions accept only failures, not the whole result.
  • Network and Timeout carry no payload. The UI doesn't need the stack trace to show "check your connection."
  • Serialization and Unknown keep the cause. These are bugs, not user problems, so you want them in your crash reporting.
  • Http carries a parsed ApiError. More on that below, because this is where most of the real value lives.

You could use Kotlin's built-in Result type instead, but it only holds a Throwable, so you lose exhaustive when checks over your own error categories. For a network layer, a custom sealed type pays for itself quickly.

A safeApiCall Wrapper for Retrofit in Kotlin

Now we need one place that converts thrown exceptions into ApiResult. Every repository call goes through it, so the logic is written once and tested once.

suspend fun <T> safeApiCall(call: suspend () -> T): ApiResult<T> =
    try {
        ApiResult.Success(call())
    } catch (e: CancellationException) {
        throw e // never swallow cancellation
    } catch (e: HttpException) {
        ApiResult.Failure.Http(
            code = e.code(),
            error = parseError(e.response()?.errorBody())
        )
    } catch (e: SocketTimeoutException) {
        ApiResult.Failure.Timeout
    } catch (e: IOException) {
        ApiResult.Failure.Network
    } catch (e: SerializationException) {
        ApiResult.Failure.Serialization(e)
    } catch (e: Exception) {
        ApiResult.Failure.Unknown(e)
    }

Order matters. SocketTimeoutException extends IOException, so it has to be caught first or it will be classified as a generic network failure. And CancellationException must be rethrown before anything else gets a chance to catch it.

Don't swallow cancellation

If you catch CancellationException and return a Failure, a cancelled coroutine keeps running as if nothing happened. You'll see ghost updates to state after a screen is gone, and in some cases leaks. Always rethrow it.

Using it in a repository is then trivial:

class ProfileRepository(private val api: ProfileApi) {
    suspend fun getProfile(): ApiResult<Profile> =
        safeApiCall { api.getProfile() }

    suspend fun updateName(name: String): ApiResult<Profile> =
        safeApiCall { api.updateProfile(UpdateProfileRequest(name)) }
}

Alternative: Response<T>

Some teams prefer declaring Retrofit functions as returning Response<T> and checking isSuccessful manually. That works, but you still need try/catch for IOException, so you end up with two error paths. A single wrapper around plain suspend functions keeps things simpler.

Parsing Error Bodies From Your Backend

This is the part most tutorials skip, and it's where I get the most leverage because I also build backends in Node.js and Laravel. A 422 from a Laravel API isn't just "error 422." It usually contains a message and a map of field-level validation errors. If you throw that away, you can't tell the user which field is wrong.

Agree on an error envelope with your backend team (or with yourself, if you're full-stack) and parse it:

@Serializable
data class ApiError(
    val message: String? = null,
    val code: String? = null,
    val errors: Map<String, List<String>> = emptyMap()
)

private val errorJson = Json { ignoreUnknownKeys = true }

fun parseError(body: ResponseBody?): ApiError? =
    body?.use {
        runCatching { errorJson.decodeFromString<ApiError>(it.string()) }
            .getOrNull()
    }

Some notes from real projects:

  • Parsing must never throw. Proxies, CDNs and load balancers sometimes return HTML error pages. runCatching ensures a malformed body becomes null, not a crash.
  • Read the body once. errorBody() is a stream. Consuming it twice returns an empty string.
  • Prefer a machine-readable code over the message. A field like "code": "EMAIL_TAKEN" lets the app show a localized message instead of whatever English string the server sent.

When I've worked on apps where the backend returned inconsistent error shapes across endpoints, fixing the contract on the server side saved far more time than writing clever parsing on the client. If you have any influence over the API, use it here.

Mapping Errors to UI State in Jetpack Compose

The ViewModel's job is to turn a technical failure into something a user can act on. I keep this mapping in one extension function so every screen speaks the same language.

sealed interface ErrorUi {
    data object NoConnection : ErrorUi
    data object Timeout : ErrorUi
    data object SessionExpired : ErrorUi
    data class Validation(val fields: Map<String, String>) : ErrorUi
    data class Message(@StringRes val resId: Int) : ErrorUi
}

fun ApiResult.Failure.toErrorUi(): ErrorUi = when (this) {
    ApiResult.Failure.Network -> ErrorUi.NoConnection
    ApiResult.Failure.Timeout -> ErrorUi.Timeout
    is ApiResult.Failure.Http -> when (code) {
        401 -> ErrorUi.SessionExpired
        422 -> ErrorUi.Validation(
            error?.errors?.mapValues { it.value.first() }.orEmpty()
        )
        in 500..599 -> ErrorUi.Message(R.string.error_server)
        else -> ErrorUi.Message(R.string.error_generic)
    }
    is ApiResult.Failure.Serialization,
    is ApiResult.Failure.Unknown -> ErrorUi.Message(R.string.error_generic)
}

And in the ViewModel:

fun saveName(name: String) {
    viewModelScope.launch {
        _state.update { it.copy(isSaving = true, error = null) }
        when (val result = repository.updateName(name)) {
            is ApiResult.Success -> _state.update {
                it.copy(isSaving = false, profile = result.data)
            }
            is ApiResult.Failure -> {
                if (result is ApiResult.Failure.Serialization ||
                    result is ApiResult.Failure.Unknown) {
                    crashReporter.log(result)
                }
                _state.update {
                    it.copy(isSaving = false, error = result.toErrorUi())
                }
            }
        }
    }
}

Your composable then renders ErrorUi however fits the screen: an inline message under a text field for Validation, a retry banner for NoConnection, a navigation event to login for SessionExpired. The composable never sees an exception, an HTTP code, or a raw server string.

Where 401 handling really belongs

Mapping 401 to SessionExpired in the UI is a fallback. In most apps I build, token refresh lives in an OkHttp Authenticator, so the UI only sees a 401 when refresh itself has failed. That keeps screens free of auth logic entirely.

Testing Retrofit Error Handling With MockWebServer

The biggest benefit of centralizing Retrofit error handling is that you can test it properly once. OkHttp's MockWebServer lets you simulate real server behavior, including bad bodies and dropped connections, without mocking Retrofit itself.

class ProfileRepositoryTest {
    private val server = MockWebServer()
    private lateinit var repository: ProfileRepository

    @Before fun setup() {
        server.start()
        val api = Retrofit.Builder()
            .baseUrl(server.url("/"))
            .addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
            .build()
            .create(ProfileApi::class.java)
        repository = ProfileRepository(api)
    }

    @After fun teardown() = server.shutdown()

    @Test fun `422 is parsed into validation errors`() = runTest {
        server.enqueue(
            MockResponse().setResponseCode(422).setBody(
                """{"message":"Invalid","errors":{"name":["Name is required"]}}"""
            )
        )
        val result = repository.updateName("")
        val http = result as ApiResult.Failure.Http
        assertEquals("Name is required", http.error?.errors?.get("name")?.first())
    }

    @Test fun `dropped connection maps to Network`() = runTest {
        server.enqueue(MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START))
        assertEquals(ApiResult.Failure.Network, repository.getProfile())
    }

    @Test fun `html error page does not crash`() = runTest {
        server.enqueue(MockResponse().setResponseCode(502).setBody("<html>Bad Gateway</html>"))
        val http = repository.getProfile() as ApiResult.Failure.Http
        assertNull(http.error)
    }
}

These three tests cover the scenarios that most often cause production crashes in the apps I've audited: validation responses, flaky connectivity and non-JSON gateway errors. Add a timeout case using setBodyDelay with a short client read timeout, and you've covered the whole sealed hierarchy.

From a freelancing perspective, this is also the kind of work that builds trust with clients. When I'm handed an unstable app, being able to say "every network call now goes through one tested path" is a concrete, explainable improvement, far more convincing than "I fixed some crashes."

Key Takeaways

  • Don't let exceptions leave your data layer. Return a sealed ApiResult so the compiler forces every failure case to be handled.
  • Wrap every Retrofit call in one safeApiCall. Catch specific exceptions in the right order and always rethrow CancellationException.
  • Parse error bodies defensively. Agree on an error envelope with your backend, and make sure malformed or HTML bodies become null, not crashes.
  • Map failures to user-actionable UI states. Composables should render ErrorUi, never exceptions or raw HTTP codes.
  • Test the network layer with MockWebServer. Simulating real server responses catches the edge cases that unit mocks miss.