Error handling and result types
Why it matters
- An uncaught
SerializationExceptionorHttpExceptioncrashes the app, and a generic "something went wrong" hides which layer failed; a sealed result gives the UI a typed branch for each failure mode. - Interviewers ask what happens when you catch
CancellationExceptionor wrap a suspend call inrunCatching; the answer shows whether you understand cooperative cancellation. - Retrying a POST after a timeout can create a duplicate order; knowing which HTTP methods are idempotent is a common senior-level question.
- A
whenover a sealed type must handle every case, so adding a new error variant shows you every place that needs to deal with it.
The simple explanation
- A restaurant kitchen sends back one of four tickets: "here is your food" (Ok), "we could not reach the kitchen" (Network), "we do not have that dish" (Http 404), "the ticket is unreadable" (Parse).
- The waiter must tell the customer which ticket they got, not just say "sorry".
- If the customer cancels the order, nobody writes an apology ticket; the order is simply dropped (CancellationException is not an error to report).
- You do not re-send the same steak order three times when you are not sure whether the kitchen got it (a non-idempotent POST must not be retried blindly).
- A sealed interface is the menu of possible tickets; the compiler checks that the waiter handles every ticket type.
In a Retrofit call three different things can go wrong: the request does not complete (IOException), the server answers with a non-2xx status (HttpException for a bare T return type, or a Response with isSuccessful == false), or the body cannot be converted (SerializationException with kotlinx.serialization). Map each to its own subtype so the UI can react differently.
| Exception | Cause | Sealed variant |
|---|---|---|
IOException | No network, DNS failure, timeout, connection reset | Network |
HttpException / non-2xx Response | 4xx, 5xx | Http |
SerializationException | Malformed JSON, missing field, unknown key | Parse |
CancellationException | The coroutine's scope was cancelled (screen closed) | re-throw, do not map |
CancellationException is how coroutines stop. Catching it does not un-cancel the coroutine, but the function returns normally, so the caller keeps running: it may show a false error, write state for a screen that is gone, or start a retry. catch (e: Exception) and runCatching { } both catch it. Either re-throw it before your general catch, or catch only the specific exceptions you map.
Retry with exponential backoff only for idempotent methods (GET, HEAD, PUT, DELETE) and only for transient failures (network errors, 503). Retrying a POST that timed out can repeat an action the server already did. For POSTs that must be retried, send a client-generated idempotency key so the server can drop duplicates.
With Response<T>, body() is null for every non-2xx response (the error is in errorBody()) and can also be null on 2xx for 204 and 205 responses. errorBody() can be read once. Log the exception class and HTTP code, never the auth token or personal data.
Notes
- A sealed interface with
Ok,Network,Http,ParseandUnknownsubtypes covers the failure paths; awhenover it must handle every subtype, without anelse. - Never let
CancellationExceptionbecome an error result. Re-throw it before anycatch (e: Exception), or catch only specific exceptions. runCatchingcatches everyThrowable, includingCancellationException. Around suspend calls, re-throw it fromonFailureor use your ownsafeCallinstead.withTimeoutthrowsTimeoutCancellationException, which is aCancellationException. UsewithTimeoutOrNullif a timeout should become a value.IOExceptioncovers connection failures, DNS errors and timeouts.HttpExceptionis thrown for non-2xx only when the Retrofit function returns the body type directly; withResponse<T>, checkisSuccessful.SerializationExceptionis anIllegalArgumentException, not anIOException, so the catch order between them does not matter. With Moshi, malformed JSON throwsJsonEncodingException, which is anIOException, so put a Moshi catch before theIOExceptionbranch.- Idempotent methods:
GET,HEAD,PUT,DELETE,OPTIONS.POSTandPATCHare not; retry them only with an idempotency key the server honours. response.body()isT?: null for any non-2xx response and for 204/205. CheckisSuccessfulfirst; useResponse<Unit>for endpoints that return no content.errorBody()is one-shot: read it once withstring()and keep the result.- A plain
Result<T>has a success value or aThrowable; a sealed type names each failure and can carry typed data such as the HTTP code.
Code example
This shows a sealed ApiResult type, a safeCall wrapper that maps each failure to a variant and re-throws cancellation, and a retry helper for idempotent calls.
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.serialization.SerializationException
import retrofit2.HttpException
import retrofit2.Response
import java.io.IOException
import kotlin.random.Random
sealed interface ApiResult<out T> {
data class Ok<T>(val data: T) : ApiResult<T>
data class Network(val cause: IOException) : ApiResult<Nothing>
data class Http(val code: Int, val errorBody: String?) : ApiResult<Nothing>
data class Parse(val cause: SerializationException) : ApiResult<Nothing>
data class Unknown(val cause: Exception) : ApiResult<Nothing>
}
suspend fun <T> safeCall(block: suspend () -> Response<T>): ApiResult<T> =
try {
val response = block()
if (response.isSuccessful) {
val body = response.body()
if (body != null) ApiResult.Ok(body)
else ApiResult.Unknown(IllegalStateException("Empty body, HTTP " + response.code()))
} else {
ApiResult.Http(response.code(), response.errorBody()?.string()) // read once
}
} catch (e: CancellationException) {
throw e // cancellation is not a failure
} catch (e: HttpException) {
ApiResult.Http(e.code(), null) // if block calls a function returning a bare T
} catch (e: IOException) {
ApiResult.Network(e)
} catch (e: SerializationException) {
ApiResult.Parse(e)
} catch (e: Exception) {
ApiResult.Unknown(e)
}
// Only for idempotent requests (GET, PUT, DELETE). Retries network errors and 503.
suspend fun <T> retrying(
maxAttempts: Int = 3,
baseDelayMs: Long = 500,
block: suspend () -> ApiResult<T>,
): ApiResult<T> {
var attempt = 1
while (true) {
val result = block()
val transient = result is ApiResult.Network || (result is ApiResult.Http && result.code == 503)
if (!transient || attempt == maxAttempts) return result
// 500 ms, 1 s, ... plus random jitter so many clients do not retry in sync
delay(baseDelayMs * (1L shl (attempt - 1)) + Random.nextLong(baseDelayMs))
attempt++
}
}
// Usage: val user = retrying { safeCall { api.getUser(id) } }CancellationExceptionis re-thrown before the generalcatch (e: Exception); without that line the last branch would turn cancellation intoUnknown.HttpExceptionis inretrofit2. It is only thrown for functions that return the body type directly; aResponse<T>brings non-2xx back in the object.delayis cancellable, so cancelling the scope during a backoff stops the retry loop immediately.- The retry helper does not know the HTTP method. Only wrap idempotent calls with it.
Run the idea in plain Kotlin
This uses stand-in exception classes to show the mapping, a retry that succeeds on the third attempt, and the difference between runCatching and safeCall when the coroutine is cancelled.
import java.io.IOException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
// Stand-ins for retrofit2.HttpException and kotlinx.serialization.SerializationException
class HttpException(val code: Int) : Exception("HTTP " + code)
class SerializationException(message: String) : IllegalArgumentException(message)
sealed interface ApiResult<out T> {
data class Ok<T>(val data: T) : ApiResult<T>
data class Network(val reason: String) : ApiResult<Nothing>
data class Http(val code: Int) : ApiResult<Nothing>
data class Parse(val reason: String) : ApiResult<Nothing>
}
suspend fun <T> safeCall(block: suspend () -> T): ApiResult<T> =
try {
ApiResult.Ok(block())
} catch (e: CancellationException) {
throw e
} catch (e: HttpException) {
ApiResult.Http(e.code)
} catch (e: IOException) {
ApiResult.Network(e.message ?: "io")
} catch (e: SerializationException) {
ApiResult.Parse(e.message ?: "parse")
}
suspend fun <T> retrying(maxAttempts: Int, block: suspend () -> ApiResult<T>): ApiResult<T> {
var attempt = 1
while (true) {
val result = block()
if (result !is ApiResult.Network || attempt == maxAttempts) return result
println(" attempt " + attempt + " failed, retrying")
delay(10L * (1L shl (attempt - 1)))
attempt++
}
}
fun main() = runBlocking {
println(safeCall { "User-42" })
println(safeCall<String> { throw HttpException(404) })
println(safeCall<String> { throw SerializationException("missing field 'name'") })
var calls = 0
val flaky = retrying(maxAttempts = 3) {
safeCall {
calls++
if (calls < 3) throw IOException("timeout") else "User-7"
}
}
println("after " + calls + " calls: " + flaky)
// Cancellation: runCatching swallows it, safeCall re-throws it
val job1 = launch {
val r = runCatching { delay(1_000); "late" }
println("runCatching swallowed cancellation: " + (r.exceptionOrNull() is CancellationException))
}
val job2 = launch {
safeCall { delay(1_000); "late" }
println("never printed")
}
delay(50)
job1.cancel()
job2.cancel()
job1.join()
job2.join()
println("job2 cancelled cleanly: " + job2.isCancelled)
}Expected output:
Ok(data=User-42)
Http(code=404)
Parse(reason=missing field 'name')
attempt 1 failed, retrying
attempt 2 failed, retrying
after 3 calls: Ok(data=User-7)
runCatching swallowed cancellation: true
job2 cancelled cleanly: true
In production
- Users reported double charges after confirming a payment on a slow connection.
- The dashboard showed pairs of identical
POST /ordersrequests a few seconds apart. - The app retried any request on
IOException. A read timeout happened after the server had already created the order, so the retry created a second one, and the server had no deduplication.
- The app generates a UUID per order attempt and sends it as an
Idempotency-Keyheader, reusing the same key for every retry of that attempt. - The server stores keys for a time window and returns the original result for a repeated key.
- The generic retry helper is now used only for GET, PUT and DELETE; order submission retries only with the idempotency key.
- A test with
MockWebServerdelays the first response past the timeout and asserts that both requests carry the same key.
- Users saw the app close when the backend returned HTTP 500 during an incident.
- Crash logs showed a
NullPointerExceptionatresponse.body()!!. - The code did not check
isSuccessful. For any non-2xx responsebody()is null and the error is inerrorBody(), so the force-unwrap crashed.
- Replaced the direct
body()!!with thesafeCallwrapper, which checksisSuccessfuland maps non-2xx toApiResult.Httpwith the code and error body. - Changed an endpoint that returns 204 No Content to
Response<Unit>, so its null body is no longer an error. - Added unit tests for a 500 with an empty body, a 404 with a JSON error body, and a 204.
Common mistakes
- Catching CancellationException and returning a default value. Cancellation becomes a fake failure, and the caller continues working for a screen that is gone. Re-throw it before any general catch.
- Wrapping suspend calls in runCatching.
runCatchingcatchesCancellationException(and evenErrors likeOutOfMemoryError). Use asafeCallthat re-throws cancellation, or re-throw it inonFailure. - Retrying POST or PATCH on IOException. A timeout does not mean the server did nothing. Retry only idempotent methods, or POST with an idempotency key.
- Using response.body()!! without checking isSuccessful.
body()is null for every non-2xx response and for 204/205. CheckisSuccessfuland map errors to anHttpvariant. - Reading errorBody() twice. The error body is one-shot; the second read returns nothing or fails. Read it once and keep the string.
- Putting a broad catch first. A
catch (e: Exception)above the specific catches makes the typed branches below unreachable, and catchingThrowablealso catches JVM errors. Order:CancellationException, specific exceptions, thenException. - Logging the auth token or request body in error logs. Log the exception class, HTTP code and a correlation ID only.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What happens if you catch CancellationException and return a default value instead of re-throwing it?”
“How do you map Retrofit and OkHttp exceptions to a UI-friendly result type?”
“When should you retry a network call, and how do you avoid duplicate side effects?”
“Sealed class, sealed interface, and Result<T> from the standard library: when do you use each?”
Quiz
What should you do with a CancellationException inside a suspend function's try-catch?
Which HTTP methods are safe to retry without a server-side idempotency key?
A Retrofit function returns Response<User> and the server answers 500 with a JSON error. What does response.body() return?
What is the main advantage of a sealed result type over the standard library Result<T>?
0 of 4 answered
Mini task
Add a typed result to one API call (15 min)
- Create a sealed interface
ApiResult<out T>with five subtypes:Ok<T>,Network,Http,Parse,Unknown. Put it in aresultpackage. - Write a
suspend fun <T> safeCall(block: suspend () -> Response<T>): ApiResult<T>that checksisSuccessful, readserrorBody()once, re-throwsCancellationException, and mapsHttpException,IOException,SerializationExceptionand finallyException. - Pick one existing Retrofit call in your project. Wrap it with
safeCalland update the calling ViewModel to show a distinct UI state for network error, server error and parse error. - Write a unit test that returns
Response.error(500, "".toResponseBody())from the block and asserts the result isApiResult.Http(500, ""). - Write a second test that calls
safeCall<String> { throw CancellationException("cancelled") }and asserts withassertFailsWith<CancellationException>that it is re-thrown, not mapped. - Search the codebase for
runCatchingandcatch (e: Exception)around suspend calls and fix any that swallow cancellation.
Done condition: all tests pass, the UI shows a different message for a network error, a server error and a parse error, and no catch block or runCatching turns CancellationException into an error result.