When crash reports show CorruptionException from a DataStore file, what happens by default, and how do ReplaceFileCorruptionHandler and a catch on data change it?
answer
- CorruptionException extends IOException
- thrown by the Serializer's readFrom
- no handler: every read fails
- replace the file with fresh data
- catch hides, does not repair
basics
~20 sBy default DataStore does not recover: every read of a corrupt file throws CorruptionException, and updates fail too. A ReplaceFileCorruptionHandler writes replacement data over the file and swallows the error; a catch on data only hides it.
solid answer
~40 s`CorruptionException` is an `IOException` that a `Serializer`'s `readFrom` throws when the bytes cannot be parsed; the built-in Preferences serializer does this, and a custom one must wrap its parser's exception in it. Without a handler, DataStore rethrows it: the `data` Flow throws, collecting again retries and fails again, and `updateData` fails because it reads first. Passing `corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() }` to the delegate or factory makes DataStore check the file is still corrupt, write the handler's value over it and carry on; if that write fails, the original exception is rethrown with the write error suppressed. A `.catch { if (it is IOException) emit(emptyPreferences()) else throw it }` on `data` keeps the UI alive but leaves the file corrupt, so writes keep failing.
code
kotlin · 27 linesimport android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import java.io.IOException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
val Context.readerSettings: DataStore<Preferences> by preferencesDataStore(
name = "reader_settings",
corruptionHandler = ReplaceFileCorruptionHandler { e ->
Log.w("ReaderSettings", "Settings file was corrupt; resetting to defaults", e)
emptyPreferences()
},
)
private val FONT_SIZE = intPreferencesKey("font_size")
fun fontSize(context: Context): Flow<Int> =
context.readerSettings.data
.catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e }
.map { prefs -> prefs[FONT_SIZE] ?: 16 }go deeper
Recall that CorruptionException means the file could not be parsed and that ReplaceFileCorruptionHandler is how you opt into recovery.
Explain the flow: readFrom throws CorruptionException, DataStore calls the handler, rechecks the file under the lock and writes the replacement.
Diagnose the crash: no handler, a serializer not wrapping its parser exception, or a catch that hides corruption while writes keep failing.
Decide what the team accepts on corruption, a silent reset or a logged reset, and how the rate is monitored after release.
## What corruption means to DataStore A DataStore file is corrupt when its bytes cannot be turned back into a value. DataStore learns this from the **`Serializer`**: its `readFrom` must throw **`CorruptionException`**, a subclass of `IOException`, when the data is unparseable. The class documentation is precise about scope: a transient I/O problem or a permissions error is **not** corruption and should not be reported as `CorruptionException`. - Preferences DataStore's built-in serializer throws `CorruptionException` for an unreadable file. - A custom `Serializer` must catch its parser's exception, such as `InvalidProtocolBufferException` or `SerializationException`, and rethrow it wrapped in `CorruptionException`. If it lets the original exception escape, DataStore does not treat the failure as corruption and no corruption handler runs. ## The default: no recovery The Android guide states it plainly: by default DataStore does not recover from corruption, and attempts to read throw a `CorruptionException`. Concretely: - the `data` Flow throws the exception to every collector; - collecting again retries the read, which fails again because the file is unchanged; - `updateData` and `edit` read the current value first, so they fail too. The app is stuck on that file until it is replaced, deleted, or the user clears app data. The crash reports you see are usually collectors with no error handling. ## ReplaceFileCorruptionHandler You opt into recovery by passing a handler when the store is created, through the `corruptionHandler` parameter of `preferencesDataStore`, `dataStore`, `DataStoreFactory.create` or `MultiProcessDataStoreFactory.create`: ```kotlin corruptionHandler = ReplaceFileCorruptionHandler { e -> emptyPreferences() } ``` When a read hits `CorruptionException`, DataStore: 1. calls your lambda with the exception to produce **replacement data**; 2. takes the write lock and **re-reads the file**, in case another writer already fixed it; 3. if the file is still corrupt, **writes the replacement** to disk, swallows the original exception, and continues with that value; 4. if writing the replacement fails, it adds the write error as a **suppressed exception** and rethrows the original `CorruptionException`. Two cautions from the API docs and from practice: - the handler must **not call DataStore APIs** on that store; the `CorruptionHandler` contract warns this can deadlock; - replacement means **data loss** for that file: the user's settings go back to whatever you return. Log it, with the exception as the cause, so the rate is visible. ## A catch on data is not a repair Many codebases wrap reads like this: ```kotlin dataStore.data.catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e } ``` | Approach | UI keeps working | File repaired | Writes work | |---|---|---|---| | No handler, no catch | No, the collector throws | No | No | | `catch` on `data` only | Yes, with defaults | No | No | | `ReplaceFileCorruptionHandler` | Yes | Yes, with your replacement | Yes | Because `CorruptionException` is an `IOException`, the `catch` also swallows corruption. It is still worth having for transient I/O failures, but on its own it leaves the store broken for every later write. ## Reducing corruption in the first place - Keep the type immutable and the serializer deterministic. - Follow the one-instance-per-file rule: duplicate instances racing on one file are a classic source of bad bytes. - Stay on a current release. In 1.1.4 and 1.1.5, Preferences DataStore's default storage moved from `OkioStorage` to `FileStorage`, a change made specifically to reduce `CorruptionException` reports. ## Testing and monitoring recovery Corruption is rare, so the recovery path is easy to ship untested. Treat it like any other error path: 1. In an instrumented test, write a few garbage bytes into the store's file before the first read, then collect `data` and assert that the handler's replacement value arrives. 2. Assert that a following `edit` or `updateData` succeeds, which proves the file was actually replaced rather than hidden by a `catch`. 3. For a custom `Serializer`, add a unit test that feeds `readFrom` invalid input and expects `CorruptionException`. 4. In production, log every handler call with the exception as its cause and watch the rate per release; a jump after an update usually means a serializer or schema change that old files no longer decode.
- Your custom Serializer lets a SerializationException escape from readFrom; what changes?DataStore only routes `CorruptionException` to the corruption handler, so the raw `SerializationException` propagates as an ordinary read failure: the `data` Flow throws it, `updateData` fails, and a configured `ReplaceFileCorruptionHandler` never runs. Wrap the parser exception in `CorruptionException` inside `readFrom`.
- Could readFrom just return defaultValue when parsing fails?It would avoid the exception, but silently: DataStore would treat the default as the stored value, nothing would be logged, and the next update would overwrite the old bytes. Throwing `CorruptionException` and replacing through a handler gives the same recovery with a visible, loggable event.
- DataStore resets a corrupt file to the Serializer's defaultValue automatically.
- Any IOException from readFrom triggers the corruption handler.
- A catch on the data Flow repairs the corrupt file.
- The corruption handler can read the same DataStore to build its replacement.
- If writing the replacement fails, DataStore keeps the replacement in memory.
Assumes DataStore 1.2.1, where the delegates and factories accept a ReplaceFileCorruptionHandler; Preferences DataStore has used FileStorage by default since 1.1.4 and 1.1.5 to cut CorruptionException reports.