Error handling and result types

Learn Android error handling and Kotlin result types to map failures to sealed classes, manage CancellationException, and retry idempotent calls. About 25 minutes.

Why it matters

  • An uncaught SerializationException or HttpException crashes 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 CancellationException or wrap a suspend call in runCatching; 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 when over 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.

ExceptionCauseSealed variant
IOExceptionNo network, DNS failure, timeout, connection resetNetwork
HttpException / non-2xx Response4xx, 5xxHttp
SerializationExceptionMalformed JSON, missing field, unknown keyParse
CancellationExceptionThe 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, Parse and Unknown subtypes covers the failure paths; a when over it must handle every subtype, without an else.
  • Never let CancellationException become an error result. Re-throw it before any catch (e: Exception), or catch only specific exceptions.
  • runCatching catches every Throwable, including CancellationException. Around suspend calls, re-throw it from onFailure or use your own safeCall instead.
  • withTimeout throws TimeoutCancellationException, which is a CancellationException. Use withTimeoutOrNull if a timeout should become a value.
  • IOException covers connection failures, DNS errors and timeouts. HttpException is thrown for non-2xx only when the Retrofit function returns the body type directly; with Response<T>, check isSuccessful.
  • SerializationException is an IllegalArgumentException, not an IOException, so the catch order between them does not matter. With Moshi, malformed JSON throws JsonEncodingException, which is an IOException, so put a Moshi catch before the IOException branch.
  • Idempotent methods: GET, HEAD, PUT, DELETE, OPTIONS. POST and PATCH are not; retry them only with an idempotency key the server honours.
  • response.body() is T?: null for any non-2xx response and for 204/205. Check isSuccessful first; use Response<Unit> for endpoints that return no content.
  • errorBody() is one-shot: read it once with string() and keep the result.
  • A plain Result<T> has a success value or a Throwable; 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) } }
  • CancellationException is re-thrown before the general catch (e: Exception); without that line the last branch would turn cancellation into Unknown.
  • HttpException is in retrofit2. It is only thrown for functions that return the body type directly; a Response<T> brings non-2xx back in the object.
  • delay is 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

Duplicate orders from POST retry
  • Users reported double charges after confirming a payment on a slow connection.
  • The dashboard showed pairs of identical POST /orders requests 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 fix
  • The app generates a UUID per order attempt and sends it as an Idempotency-Key header, 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 MockWebServer delays the first response past the timeout and asserts that both requests carry the same key.
Crash on server errors
  • Users saw the app close when the backend returned HTTP 500 during an incident.
  • Crash logs showed a NullPointerException at response.body()!!.
  • The code did not check isSuccessful. For any non-2xx response body() is null and the error is in errorBody(), so the force-unwrap crashed.
The fix
  • Replaced the direct body()!! with the safeCall wrapper, which checks isSuccessful and maps non-2xx to ApiResult.Http with 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. runCatching catches CancellationException (and even Errors like OutOfMemoryError). Use a safeCall that re-throws cancellation, or re-throw it in onFailure.
  • 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. Check isSuccessful and map errors to an Http variant.
  • 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 catching Throwable also catches JVM errors. Order: CancellationException, specific exceptions, then Exception.
  • 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)

  1. Create a sealed interface ApiResult<out T> with five subtypes: Ok<T>, Network, Http, Parse, Unknown. Put it in a result package.
  2. Write a suspend fun <T> safeCall(block: suspend () -> Response<T>): ApiResult<T> that checks isSuccessful, reads errorBody() once, re-throws CancellationException, and maps HttpException, IOException, SerializationException and finally Exception.
  3. Pick one existing Retrofit call in your project. Wrap it with safeCall and update the calling ViewModel to show a distinct UI state for network error, server error and parse error.
  4. Write a unit test that returns Response.error(500, "".toResponseBody()) from the block and asserts the result is ApiResult.Http(500, "").
  5. Write a second test that calls safeCall<String> { throw CancellationException("cancelled") } and asserts with assertFailsWith<CancellationException> that it is re-thrown, not mapped.
  6. Search the codebase for runCatching and catch (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.

Next: Auth tokens and interceptors