Android
Passing Structured Failure Data Out of a WorkManager Worker
Result.failure() tells the UI a worker failed. It does not tell the UI what failed. workDataOf() attaches typed output to a failure result so the caller knows exactly which files were not downloaded.
- Published
- Reading
- 5 min
- Author
- Fidelis Uwem Joseph
Series · Part 7 of 8WorkManager in Production
- Injecting Dependencies into WorkManager Workers with Hilt
- WorkerTags — A Central Contract Between WorkManager Scheduler and UI Observer
- Seeding a Room Database with a WorkManager Phased Dependency Graph
- A Base Worker Template for Batched Room Inserts with Retry and Progress
- Orchestrating Android DownloadManager from a WorkManager CoroutineWorker
- Protecting Downloaded Files with a Rename-to-Backup Strategy
- Passing Structured Failure Data Out of a WorkManager Worker
- Bridging WorkManager and Compose UI via a Listener-based ProgressRepository
Result.failure() from a CoroutineWorker signals that the work is done and
did not succeed. Without output data attached, the UI knows the worker failed
but not why, which limits what it can show the user or log. workDataOf()
attaches a key-value payload to the result — readable from the UI via
WorkInfo.outputData — making the failure actionable instead of opaque.
Prerequisites
WorkManager 2.11.1. Familiarity with DownloadFilesWorker from Part 5 and
WorkManager observation via getWorkInfosByTagLiveData.
Background
DownloadFilesWorker downloads seven JSON files in a single run. Any subset of
those files can fail — the server returns an error for one file, the device
storage fills up partway through, one URL is stale. Returning Result.failure()
with no context tells the UI “something went wrong” and nothing else.
Attaching the list of failed file names to the output data lets the UI display a specific message (“categories and parts failed to download”), lets Sentry capture the exact failed files, and makes debugging vastly faster when reviewing a support ticket.
Implementation
1. Define output data keys as constants
companion object { const val KEY_PROGRESS = "download_progress" // progress output const val KEY_FAILED_FILES = "failed_files" // failure output}Keys are const val strings on the companion object, not inline literals.
The UI observes WorkInfo.outputData.getStringArray(KEY_FAILED_FILES) — it
needs the same string, and referencing the companion object constant keeps them
in sync.
2. Attach failure data to Result.failure()
is DownloadResult.SomeFailed -> { Timber.e("Downloads failed: ${result.failedNames}") Result.failure( workDataOf(KEY_FAILED_FILES to result.failedNames.toTypedArray()) )}workDataOf() accepts vararg Pair<String, Any?>. Supported value types are
primitives (Boolean, Byte, Int, Long, Float, Double), String,
and their array variants. List<String> is not directly supported — hence
.toTypedArray() to convert List<String> to Array<String>.
3. Attach progress data to setProgress()
Output data is for terminal results (success or failure). In-progress updates
use setProgress() instead:
val completed = total - pending.sizesetProgress(workDataOf(KEY_PROGRESS to (completed * 100 / total)))setProgress() can be called repeatedly during doWork(). Each call updates
WorkInfo.progress, which the UI can observe reactively. setOutputData()
(or the data passed to Result.success() / Result.failure()) is a terminal
write — it is available after the worker finishes.
4. Observing output data in the UI
val syncError: StateFlow<String?> = workManager.getWorkInfosByTagFlow(WorkerTags.DOWNLOAD_ONCE_WORKER) .map { infos -> infos.firstOrNull { it.state == WorkInfo.State.FAILED } ?.outputData ?.getStringArray(DownloadFilesWorker.KEY_FAILED_FILES) ?.takeIf { it.isNotEmpty() } ?.let { "Failed to download: ${it.joinToString()}" } } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)Two details matter here. The observer uses getWorkInfosByTagFlow scoped to
viewModelScope rather than observeForever, which would leak the observer
for the life of the process. And it observes a one-time download request,
DOWNLOAD_ONCE_WORKER, not the daily periodic one — see the danger note
below.
outputData is a Data object. getStringArray(key) returns null if the
key is absent or was never written. The ?: emptyArray() guard handles the
case where Result.failure() was called without output data — which can happen
if the worker throws an unexpected exception before reaching the
SomeFailed branch.
5. Success output data
Output data is not limited to failures. A success result can carry a summary:
Result.success( workDataOf("rows_inserted" to totalInserted))The UI can read this to display “12,450 parts loaded” after the database workers complete, without the workers needing to write to a shared data store.
6. Data size limit
// WorkManager enforces a 10KB limit on Data objects// A list of 100 file names averaging 20 chars each = ~2KB — within the limitData objects have a hard 10KB size limit. For the file-name list use case
(seven filenames, each under 30 characters), this is not a constraint. For
larger payloads, write to a shared store (DataStore, Room) and pass only
a reference key as output data.
Testing
./gradlew connectedAndroidTest --tests "*.DownloadFilesWorkerOutputTest"
BUILD SUCCESSFUL in 12s4 instrumented tests completedAssert on output data directly from the WorkInfo:
val workInfo = workManager .getWorkInfosByTag(WorkerTags.DOWNLOAD_INVENTORY_WORKER) .get() .first()
assertThat(workInfo.state).isEqualTo(WorkInfo.State.FAILED)
val failed = workInfo.outputData.getStringArray(DownloadFilesWorker.KEY_FAILED_FILES)assertThat(failed).isNotNull()assertThat(failed).contains("categories")Pitfalls
Production considerations
For failure reporting to a backend, read outputData in the WorkInfo observer
and send the failed file names to Sentry or your analytics service. This gives
you aggregate failure rates per file type across your user base — the same
files tend to fail on the same device models for the same reasons
(storage pressure, network instability, specific OEM DownloadManager bugs).
Wrapping up
You now have typed output data attached to both in-progress and terminal worker
states. The UI reads WorkInfo.progress while the worker runs and
WorkInfo.outputData when it finishes. Failed file names are surfaced to the
caller layer without relying on logs.
Going deeper
Make failure data a typed contract. Raw keys scattered across worker and
ViewModel drift apart. A small value class with toData() and
fromData(Data) functions, living next to the worker, keeps the key names,
types and defaults in one place, and is trivial to unit test without
WorkManager at all.
Distinguish “failed” from “stopped”. Since WorkManager 2.9,
WorkInfo.stopReason tells you why the system stopped a worker (constraint
lost, quota, cancelled by app, and so on). A stopped worker is retried
automatically, so the UI should show “waiting for network”, not an error.
Only FAILED with your own output data deserves an error message.
Report it, but aggregate it. Sending each failure to an error tracker as a separate exception floods it. Send one event per failed sync with the file list as structured context (and the device model and free storage). Grouping then shows which files fail on which devices — usually storage pressure or a specific OEM’s DownloadManager.