Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 104 ยท Networking

Error Handling and Offline-first

Handle network failures in Android: sealed results, HTTP error mapping, retries with backoff, connectivity checks, Room as source of truth and syncing pending changes.

Networks fail. Phones go through tunnels, switch from Wi-Fi to mobile data, hit captive portals and talk to servers that sometimes return 503. An app that only works when everything goes right feels broken most of the time, so error handling is not a corner case in Android development. It is half of the data layer.

This lesson has two parts. First, you will turn raw failures (exceptions, status codes) into a small set of typed results that a ViewModel can show, and add retries with backoff for failures that are worth retrying. Second, you will make the app offline-first: the local database is the source of truth, writes succeed immediately and are synced later. Retrofit, Room and WorkManager have their own lessons, so the real Android code here is read-only. The TryIts are plain Kotlin stand-ins on Piston that show the same logic with in-memory data. The ideas build on Kotlin's Result type, sealed classes and the repository pattern.

Model failures as values

A repository can report failure in two ways: throw exceptions or return a value that says "this failed". Exceptions are easy to forget to catch, and a forgotten catch in a coroutine can crash the app. For failures you expect (no network, server error, not found), returning a value makes the compiler help you: with a sealed hierarchy, a when must handle every case.

Kotlin
// read-only sketch
sealed interface AppError {
    data object Offline : AppError                 // no connection, DNS or timeout
    data class Server(val code: Int) : AppError    // 5xx
    data class Client(val code: Int) : AppError    // 4xx: our request was wrong
    data object Unauthorized : AppError            // 401: sign in again
    data class Unknown(val cause: Throwable) : AppError
}

sealed interface Outcome<out T> {
    data class Success<T>(val value: T) : Outcome<T>
    data class Failure(val error: AppError) : Outcome<Nothing>
}

Kotlin's built-in Result<T> is similar, but it can only carry a Throwable, and a when over it cannot be exhaustive about error kinds. A small sealed type of your own says exactly which failures the UI has to care about. Keep the list short: the UI needs to tell "no internet" from "server problem" from "you need to log in", not to know every HTTP code.

Where do the conversions happen? Inside the data layer, at the boundary with Retrofit. Retrofit throws IOException for transport problems (including timeouts and UnknownHostException) and HttpException for non-2xx responses. A single function wraps each call:

Kotlin
// read-only sketch
suspend fun <T> safeApiCall(call: suspend () -> T): Outcome<T> = try {
    Outcome.Success(call())
} catch (e: CancellationException) {
    throw e                                   // never swallow cancellation
} catch (e: IOException) {
    Outcome.Failure(AppError.Offline)
} catch (e: HttpException) {
    Outcome.Failure(
        when (e.code()) {
            401 -> AppError.Unauthorized
            in 400..499 -> AppError.Client(e.code())
            in 500..599 -> AppError.Server(e.code())
            else -> AppError.Unknown(e)
        }
    )
}

Always rethrow CancellationException. A broad catch (e: Exception) that swallows it breaks structured concurrency: the coroutine looks cancelled but keeps running, and screens that were left stay busy. See Coroutines on Android.

flowchart LR
    A["Retrofit call"] --> B{"What happened?"}
    B -- "2xx" --> S["Success(value)"]
    B -- "IOException" --> O["Failure(Offline)"]
    B -- "401" --> U["Failure(Unauthorized)"]
    B -- "other 4xx" --> C["Failure(Client)"]
    B -- "5xx" --> V["Failure(Server)"]

One boundary function turns exceptions and status codes into the few outcomes the UI cares about.

Retries with backoff

Not every failure deserves a retry. A 404 will still be a 404 in two seconds, and a 400 means your request is wrong. But a dropped connection, a 503 or a 429 (too many requests) often succeed a moment later. The usual rule is: retry only the transient failures, a limited number of times, and wait longer each time. Doubling the wait (200 ms, 400 ms, 800 ms) is called exponential backoff. It stops thousands of devices from hammering a struggling server in lockstep. Real clients also add a little random jitter to the delay so devices do not retry at the same instant.

The first TryIt implements this with a scripted fake server so the output is the same every run. The waiting function is passed in; here it only adds up the time, in a test you would use virtual time, and in the app it would be delay.

Kotlin Typed errors and retry with backoff (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Check the three runs: scenario 1 waits 200 ms and then 400 ms before the third attempt succeeds. Scenario 2 stops at once because Client(404) is not retryable. Scenario 3 uses all four attempts (waits of 200, 400 and 800 ms) and then reports the last failure, so the UI can show "You are offline" instead of spinning forever.

Retrying inside the app has limits. If the user is offline, retrying every second for five minutes just burns battery. Prefer to retry a few times quickly for transient errors, then surface the error with a Retry button, and let WorkManager retry background work when the device is back online.

Telling the user what happened

The ViewModel turns the AppError into UI state. The mapping is a UI decision, so it lives in the ViewModel or a small mapper, with text from string resources:

Error What the user sees Action
Offline "You are offline. Showing saved items." Banner, plus a Retry button when nothing is saved
Server "Something went wrong on our side." Retry
Unauthorized Sign-in screen Navigate to login
Client A generic error, and a log entry for you Usually a bug in the app

If you already have data to show, keep showing it and put the error in a banner or snackbar. Replace the whole screen with an error page only when there is nothing else to display. The UI state lesson covers modeling this.

Checking connectivity

Android can tell you whether the device has a network, through ConnectivityManager. You can expose it as a Flow<Boolean> using callbackFlow (see Collecting Flows Safely):

Kotlin
// read-only sketch: requires the ACCESS_NETWORK_STATE permission (a normal permission)
fun ConnectivityManager.isOnlineFlow(): Flow<Boolean> = callbackFlow {
    val callback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) { trySend(true) }
        override fun onLost(network: Network) { trySend(false) }
    }
    registerDefaultNetworkCallback(callback)
    trySend(activeNetwork != null)
    awaitClose { unregisterNetworkCallback(callback) }
}

Use this flow to decide what to show (an "offline" banner, sync when connection returns). Do not use it as the gatekeeper for requests ("only call the server if online"). "Connected" does not mean "the server is reachable": the device can be on a Wi-Fi network without internet access, and the state can change between your check and your request. The reliable test is to make the call and handle the failure.

Offline-first: the database is the source of truth

An offline-first app reads from and writes to the local database, and treats the network as a way to synchronize it. The repository lesson introduced the read side: the UI observes a Room Flow, and refresh() writes server data into the database. Writes follow the same idea:

  1. The user saves a note. The repository writes it to the database immediately with a synced = false flag. The UI updates at once, because it observes the database.
  2. A sync step finds every unsynced row and sends it to the server. On success it sets synced = true.
  3. If the device is offline, nothing is lost. The row stays pending and the sync runs again later.
sequenceDiagram
    participant UI
    participant Repo as Repository
    participant DB as Room
    participant Net as Server
    UI->>Repo: save("Buy milk")
    Repo->>DB: insert (synced = false)
    DB-->>UI: list updates instantly
    Repo->>Net: push pending rows
    alt online
        Net-->>Repo: OK
        Repo->>DB: mark synced = true
    else offline
        Net--xRepo: IOException
        Note over Repo,DB: row stays pending, retried later
    end

Writes always succeed locally. The server catches up when it can.

Kotlin
// read-only sketch: the real shape with Room and WorkManager
interface NoteDao {
    @Query("SELECT * FROM notes ORDER BY id") fun observeAll(): Flow<List<NoteEntity>>
    @Query("SELECT * FROM notes WHERE synced = 0") suspend fun pending(): List<NoteEntity>
    @Upsert suspend fun upsert(note: NoteEntity)
}

class NoteRepository(private val dao: NoteDao, private val api: NoteApi) {
    val notes: Flow<List<Note>> = dao.observeAll().map { rows -> rows.map { it.toDomain() } }

    suspend fun save(text: String) {
        dao.upsert(NoteEntity(text = text, synced = false))
    }

    suspend fun sync(): Boolean {
        for (note in dao.pending()) {
            when (val result = safeApiCall { api.push(note.toDto()) }) {
                is Outcome.Success -> dao.upsert(note.copy(synced = true))
                is Outcome.Failure -> return false      // stop; try again later
            }
        }
        return true
    }
}

In a real app, sync() is called from a WorkManager worker with a "network connected" constraint, so Android runs it when the connection returns, even if the app was closed. The second TryIt is a stand-in where the "database" is a StateFlow, the server can be switched offline, and a collector plays the UI.

Kotlin An offline-first repository (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The UI never waited for the network. Notes saved offline appeared at once with a pending marker, and the sync step delivered them in order when the server came back. If you had pushed rows in parallel, or marked them synced before the server confirmed, you could lose data, so the order in sync() (push first, then mark) matters.

Conflicts and other sync questions

Two-way sync is harder than the demo. If the same note was edited on two devices, which version wins? Common answers are last write wins (compare timestamps, simple but can lose edits), server wins (the server's copy replaces yours), or merging by field. Pick a rule deliberately and write it down. Other things to plan for:

  • Idempotent pushes. A request may succeed on the server but the response may be lost, so you retry. Give every record a client-generated ID (a UUID) so the server can recognize a repeat instead of creating a duplicate.
  • Deletes. Mark rows as deleted (a "tombstone") until the server confirms, otherwise a refresh may bring a deleted item back.
  • Never wipe local data before new data is safely stored. Replace inside a database transaction.

Common mistakes

  • Catching Exception in suspend code and swallowing CancellationException.
  • Retrying everything, including 4xx errors, which can never succeed.
  • Retrying forever or instantly, with no limit and no backoff.
  • Checking connectivity before every call instead of handling the failure.
  • Showing a full-screen error when old data exists.
  • Letting the UI read the network response instead of the database, so the screen is empty offline.
  • Marking data as synced before the server confirms.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why return a sealed result instead of throwing for expected failures such as no network?

    With a sealed hierarchy, a when expression must cover every case, so a forgotten failure becomes a compile error instead of a crash at runtime.
  2. 2. Which failure is a good candidate for an automatic retry?

    A 503 is transient and often succeeds later. A 404 or 400 will give the same answer again, and a malformed response will not fix itself by waiting.
  3. 3. What is the main idea of offline-first?

    The UI observes the database, so it works without a network. Writes are stored locally and pushed to the server when possible.
  4. 4. Why is it risky to guard requests with 'only call the server if the device is online'?

    A device can be on a network without internet access, or lose it right after your check. Making the call and handling the failure is the reliable approach; use connectivity to inform the UI.
  5. 5. Why must the catch block rethrow CancellationException?

    Cancellation is how coroutines stop. If you catch and ignore it, the work continues after the screen is gone and parent scopes cannot finish cleanly.

Summary

  • Turn raw exceptions and status codes into a small sealed set of errors at the data-layer boundary, and let the ViewModel map them to UI state.
  • Always rethrow CancellationException; do not wrap suspend code in a blanket catch (e: Exception).
  • Retry only transient failures (offline, 5xx, 408, 429), a limited number of times, with exponential backoff and jitter.
  • Use connectivity information to inform the UI, not to decide whether to attempt a call.
  • Offline-first: the database is the source of truth, writes are local first with a pending flag, and a sync step (often a WorkManager worker) pushes them later.
  • Plan for conflicts, duplicate pushes and deletes, and never wipe local data before new data is stored.
  • The Retrofit, Room and ConnectivityManager code is read-only; the TryIts are in-memory stand-ins with the same logic.

Next: Loading Images with Coil