globalesim: typed API errors, silent 404 on status
- Commit
17759feb684de28f208ef542030f18dc05825f7c- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-24 20:15 UTC (1 month ago)
- Parents
76f603d
Diff
globalesim/build.gradle.kts
diff --git a/globalesim/build.gradle.kts b/globalesim/build.gradle.ktsindex 2e39a05416..af0757d807 100644--- a/globalesim/build.gradle.kts+++ b/globalesim/build.gradle.kts@@ -18,6 +18,7 @@ android { dependencies { // First-party backend (api.maproj.org) over pinned TLS roots. implementation(project(":library:network"))+ implementation(project(":library:log")) // Anonymous account id persistence. implementation(libs.androidx.datastore.preferences) // Credit top-ups via Stripe PaymentSheet (server creates the
globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimApi.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimApi.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimApi.ktindex 74f1fe273e..3fef7d15df 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimApi.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/data/api/EsimApi.kt@@ -4,6 +4,8 @@ import com.vayunmathur.library.network.NetworkClient import kotlinx.serialization.json.Json import kotlinx.serialization.serializer +private val HTTP_STATUS = Regex("^HTTP (\\d{3})\\b")+ /** * Thin client for our own eSIM storefront API (the esim-v1 routes on * api.maproj.org, FIRST_PARTY trust). Generic DTOs only — the reseller@@ -16,16 +18,36 @@ object EsimApi { fun url(path: String): String = BASE_URL + path + /** HTTP failure with a parsed status code. NetworkClient surfaces+ * non-2xx as `IOException("HTTP <code>: ...")`. */+ class ApiError(val statusCode: Int, message: String) : java.io.IOException(message)++ internal fun parseApiError(e: java.io.IOException): java.io.IOException {+ if (e is ApiError) return e+ val code = e.message?.let { HTTP_STATUS.find(it)?.groupValues?.getOrNull(1)?.toIntOrNull() }+ return if (code != null) ApiError(code, e.message ?: "HTTP $code") else e+ }++ private suspend inline fun <T> wrapApiErrors(crossinline block: suspend () -> T): T {+ try {+ return block()+ } catch (e: java.io.IOException) {+ throw parseApiError(e)+ }+ }+ private suspend inline fun <reified Req, reified Res> post(path: String, body: Req): Res =- NetworkClient.callJson(- url = url(path),- method = "POST",- headers = mapOf("Content-Type" to "application/json"),- body = json.encodeToString(serializer<Req>(), body),- )+ wrapApiErrors {+ NetworkClient.callJson(+ url = url(path),+ method = "POST",+ headers = mapOf("Content-Type" to "application/json"),+ body = json.encodeToString(serializer<Req>(), body),+ )+ } private suspend inline fun <reified Res> get(path: String): Res =- NetworkClient.getJson(url(path))+ wrapApiErrors { NetworkClient.getJson(url(path)) } suspend fun register(accountId: String): RegisterResponse = post("/esim/v1/register", RegisterRequest(accountId))
globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt
diff --git a/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt b/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.ktindex f1f777a62e..c09d9a5a85 100644--- a/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt+++ b/globalesim/src/main/java/com/vayunmathur/globalesim/platform/EsimViewModel.kt@@ -10,6 +10,7 @@ import com.vayunmathur.globalesim.data.AnonymousIdStore import com.vayunmathur.globalesim.data.api.EsimApi import com.vayunmathur.globalesim.data.api.ProfileDto import com.vayunmathur.globalesim.data.api.RateDto+import com.vayunmathur.library.log.Log import java.util.UUID import kotlinx.coroutines.launch @@ -34,15 +35,21 @@ class EsimViewModel(app: Application) : AndroidViewModel(app) { var state by mutableStateOf(EsimUiState()) private set + /** True once an initial status load completed (success or fail). */+ private var statusAttempted = false+ init { viewModelScope.launch { // Mint the anonymous id only. Provisioning happens on explicit // user action (createEsim) — never on launch, since each- // provision is a real $1.75 vendor charge. Rates are public, so- // they load immediately; status/budget wait until an eSIM exists- // (refreshAll guards on profile presence).- idStore.getOrCreate()+ // provision is a real $1.75 vendor charge. Rates are public;+ // status loads once to discover an existing eSIM, then only+ // refreshes when a profile is present (refreshAll guard).+ // TEMP-DEBUG: log the stored account id. Remove after diagnosis.+ val id = idStore.getOrCreate()+ Log.status("Esim", "stored account_id=$id") refreshRates()+ refreshStatus() } } @@ -72,10 +79,9 @@ class EsimViewModel(app: Application) : AndroidViewModel(app) { fun refreshAll() { refreshRates()- // No eSIM yet (fresh install, pre-create): status would hit- // a nonexistent account, so skip it. createEsim/transferIn call- // refreshAll again once the account exists.- if (state.profile == null) return+ // No eSIM and no load attempted yet: status runs once via init.+ // After that, skip account calls until a profile exists.+ if (state.profile == null && statusAttempted) return refreshStatus() } @@ -84,7 +90,16 @@ class EsimViewModel(app: Application) : AndroidViewModel(app) { state = state.copy(loading = true, error = null) runCatching { EsimApi.status(accountId()) } .onSuccess { state = state.copy(loading = false, profile = it.profile) }- .onFailure { state = state.copy(loading = false, error = it.message) }+ .onFailure {+ // 404 = unknown account = no eSIM created yet. Normal+ // state, not an error: show the welcome card, no snackbar.+ if (it is EsimApi.ApiError && it.statusCode == 404) {+ state = state.copy(loading = false, profile = null)+ } else {+ state = state.copy(loading = false, error = it.message)+ }+ }+ statusAttempted = true } }
globalesim/src/test/java/com/vayunmathur/globalesim/data/api/ApiErrorTest.kt
diff --git a/globalesim/src/test/java/com/vayunmathur/globalesim/data/api/ApiErrorTest.kt b/globalesim/src/test/java/com/vayunmathur/globalesim/data/api/ApiErrorTest.ktnew file mode 100644index 0000000000..d7ec56afc3--- /dev/null+++ b/globalesim/src/test/java/com/vayunmathur/globalesim/data/api/ApiErrorTest.kt@@ -0,0 +1,34 @@+package com.vayunmathur.globalesim.data.api++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertSame++class ApiErrorTest {+ @Test+ fun `parses HTTP status from NetworkClient message`() {+ val out = EsimApi.parseApiError(java.io.IOException("HTTP 404: unknown account"))+ assertIs<EsimApi.ApiError>(out)+ assertEquals(404, out.statusCode)+ }++ @Test+ fun `parses other status codes`() {+ val out = EsimApi.parseApiError(java.io.IOException("HTTP 429: upstream busy, retry soon"))+ assertIs<EsimApi.ApiError>(out)+ assertEquals(429, out.statusCode)+ }++ @Test+ fun `non-HTTP IOException passes through untouched`() {+ val original = java.io.IOException("Unable to resolve host")+ assertSame(original, EsimApi.parseApiError(original))+ }++ @Test+ fun `ApiError passes through untouched`() {+ val original = EsimApi.ApiError(404, "HTTP 404: x")+ assertSame(original, EsimApi.parseApiError(original))+ }+}