Modern Apps git

← Modern-Apps.git

ui: ErrorState shows a support error ID for exception-backed errors

Commit
f4269778d200eb5d1ee589ae62c6316e20b00ba0
Author
Vayun Mathur <[email protected]>
When
2026-11-21 08:35 UTC (15 days ago)
Parents
ac37459
ErrorState gains an optional Throwable: when present it mints
and logs an error ID via Log.errorWithId (once per distinct
throwable) and renders 'Error ID: xxxx' under the message, so a
user report can be correlated with the log line. Authored-
string states (domain messages) show no ID. Message falls back
to friendlyError when only the throwable is given - raw text
never renders. Existing call sites compile unchanged.

Verified: :library:ui 1081 tests incl. 3 new semantics tests.

Diff

library/ui/src/main/java/com/vayunmathur/library/ui/StateScreens.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/StateScreens.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/StateScreens.ktindex 9cdf35e70a..8f23373df5 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/StateScreens.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/StateScreens.kt@@ -12,13 +12,16 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp+import com.vayunmathur.library.log.Log  /**  * The three "the list isn't showing you anything" screens: nothing here,@@ -111,6 +114,17 @@ fun LoadingState(modifier: Modifier = Modifier, message: String? = null) {  * Distinct from [EmptyState] on purpose: "there is nothing" and "we could not  * find out" are different situations and should not look the same. [onRetry]  * is optional because not everything can be retried.+ *+ * Pass [error] when the failure came from a [Throwable]: it is logged once+ * (per distinct instance) via `Log.errorWithId` and the minted correlation+ * id is rendered small under the message, so a user report quoting that id+ * can be matched to the log line. [errorWithId] itself calls+ * `Log.newErrorId` internally, so the returned id is the logged one — do+ * not mint a separate id here. When [message] is null the throwable is+ * mapped through [friendlyError] (raw exception text never reaches the UI);+ * an explicit [message] still wins. Call sites that pass only authored+ * strings (domain messages, not failures to correlate) leave [error] null+ * and get no id.  */ @Composable fun ErrorState(@@ -119,7 +133,13 @@ fun ErrorState(     message: String? = null,     retryLabel: String? = null,     onRetry: (() -> Unit)? = null,+    error: Throwable? = null, ) {+    // Mint + log once per distinct throwable, not on every recomposition.+    val errorId = remember(error) {+        error?.let { Log.errorWithId("ErrorState", "ErrorState: $title", it) }+    }+    val displayMessage = message ?: if (error != null) friendlyError(error) else null     Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {         Column(             modifier = Modifier.fillMaxWidth().padding(32.dp),@@ -132,14 +152,22 @@ fun ErrorState(                 color = MaterialTheme.colorScheme.error,                 textAlign = TextAlign.Center,             )-            if (message != null) {+            if (displayMessage != null) {                 Text(-                    message,+                    displayMessage,                     style = MaterialTheme.typography.bodyMedium,                     color = MaterialTheme.colorScheme.outline,                     textAlign = TextAlign.Center,                 )             }+            if (errorId != null) {+                Text(+                    stringResource(R.string.error_id_format, errorId),+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.outline,+                    textAlign = TextAlign.Center,+                )+            }             if (onRetry != null && retryLabel != null) {                 Button(onClick = onRetry) { Text(retryLabel) }             }
library/ui/src/main/res/values/strings.xml
diff --git a/library/ui/src/main/res/values/strings.xml b/library/ui/src/main/res/values/strings.xmlindex 302db834b5..7f9fb8c66c 100644--- a/library/ui/src/main/res/values/strings.xml+++ b/library/ui/src/main/res/values/strings.xml@@ -359,4 +359,6 @@     <string name="friendly_error_parse">The response could not be read. It may be damaged or in an unexpected format.</string>     <!-- Shared library: UI - FriendlyError: fallback for every other failure. Full sentence -->     <string name="friendly_error_generic">Something went wrong. Try again.</string>+    <!-- Shared library: UI - StateScreens/ErrorState: small correlation id under a throwable-backed error, quoted in user reports to find the log line. %1$s = 8-char hex id from Log.errorWithId, e.g. 3f9a1c07 -->+    <string name="error_id_format">Error ID: <xliff:g id="error_id" example="3f9a1c07">%1$s</xliff:g></string> </resources>
library/ui/src/test/java/com/vayunmathur/library/ui/ErrorStateErrorIdTest.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/ErrorStateErrorIdTest.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/ErrorStateErrorIdTest.ktnew file mode 100644index 0000000000..e9fb151ef7--- /dev/null+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/ErrorStateErrorIdTest.kt@@ -0,0 +1,79 @@+package com.vayunmathur.library.ui++import androidx.compose.ui.semantics.SemanticsProperties+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * ErrorState error-correlation id: a throwable-backed state logs via+ * `Log.errorWithId` and renders the minted id small under the message; an+ * authored-string state (domain message, nothing to correlate) renders none.+ */+@RunWith(RobolectricTestRunner::class)+class ErrorStateErrorIdTest {++    @get:Rule+    val rule = createComposeRule()++    @Test fun throwableErrorStateRendersErrorId() {+        rule.setContent {+            ErrorState(+                title = "Broken",+                message = "Nope",+                error = IOException("raw secret https://secret.example/x"),+            )+        }+        rule.onNodeWithText("Broken").assertIsDisplayed()+        rule.onNodeWithText("Nope").assertIsDisplayed()+        // Exactly one id line, formatted 'Error ID: xxxxxxxx' (8 lowercase hex).+        val idNodes = rule.onAllNodesWithText("Error ID:", substring = true)+            .fetchSemanticsNodes()+        assertEquals(1, idNodes.size)+        val idText = idNodes.single().config[SemanticsProperties.Text]+            .joinToString("") { it.text }+        assertTrue(+            Regex("""Error ID: [0-9a-f]{8}""").matches(idText),+            "expected 'Error ID: <8 hex>', was '$idText'",+        )+        // Raw exception text never reaches the UI.+        assertTrue(+            rule.onAllNodesWithText("secret", substring = true).fetchSemanticsNodes().isEmpty(),+        )+    }++    @Test fun throwableErrorStateWithoutMessageUsesFriendlyMessageAndId() {+        rule.setContent {+            ErrorState(title = "Broken", error = IOException("raw secret"))+        }+        rule.onNodeWithText("Broken").assertIsDisplayed()+        // Friendly (offline/IO) wording, not the raw exception text.+        rule.onAllNodes(hasText("offline", substring = true)).fetchSemanticsNodes()+            .also { assertTrue(it.isNotEmpty(), "expected friendly offline message") }+        assertEquals(+            1,+            rule.onAllNodesWithText("Error ID:", substring = true).fetchSemanticsNodes().size,+        )+    }++    @Test fun authoredStringErrorStateRendersNoErrorId() {+        rule.setContent {+            ErrorState(title = "Broken", message = "That item no longer exists")+        }+        rule.onNodeWithText("Broken").assertIsDisplayed()+        rule.onNodeWithText("That item no longer exists").assertIsDisplayed()+        assertTrue(+            rule.onAllNodesWithText("Error ID:", substring = true).fetchSemanticsNodes().isEmpty(),+            "authored-string ErrorState must not render an error id",+        )+    }+}