Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

refactor: introduce HumanReadableError utility to standardize user-facing error messaging across the application

Rishabh Bajpai0b7ab05a28f3
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index fcb61c5..8e24c9a 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -114,6 +114,7 @@
</queries>
<application
+ android:name=".GotchaApp"
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
diff --git a/app/src/main/java/com/gotcha/GotchaApp.kt b/app/src/main/java/com/gotcha/GotchaApp.kt
new file mode 100644
index 0000000..e2d197f
--- /dev/null
+++ b/app/src/main/java/com/gotcha/GotchaApp.kt
@@ -0,0 +1,33 @@
+package com.gotcha
+
+import android.app.Application
+import android.util.Log
+
+/**
+ * Top-level application class registering process-wide uncaught exception
+ * diagnostic logging.
+ */
+class GotchaApp : Application() {
+
+ override fun onCreate() {
+ super.onCreate()
+ setupUncaughtExceptionHandler()
+ }
+
+ private fun setupUncaughtExceptionHandler() {
+ val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
+ Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
+ try {
+ Log.e(TAG, "Uncaught exception on thread ${thread.name}: ${throwable.message}", throwable)
+ } catch (_: Throwable) {
+ // Ensure logging itself never throws
+ }
+ // Forward to system default handler to record OS diagnostics and manage process lifecycle.
+ defaultHandler?.uncaughtException(thread, throwable)
+ }
+ }
+
+ companion object {
+ private const val TAG = "GotchaApp"
+ }
+}
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
index 4ef1eb8..7631db0 100644
--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt
+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt
@@ -24,6 +24,7 @@ import com.gotcha.tools.SubAgentSession
import com.gotcha.tools.ToolExecutor
import com.gotcha.tools.ToolRegistry
import com.gotcha.tools.ToolResult
+import com.gotcha.util.HumanReadableError
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.serialization.json.Json
@@ -40,15 +41,7 @@ private enum class ConfirmDecision { APPROVED, DENIED, TIMED_OUT }
private val WHITESPACE = Regex("\\s+")
/** Maps API/network failures to a short, user-readable message. */
-internal fun friendlyAgentError(e: Exception): String = when {
- e is retrofit2.HttpException && e.code() == 401 ->
- "The API rejected the key (401). Check your API key in settings."
- e is retrofit2.HttpException ->
- "The API returned an error (HTTP ${e.code()}). ${e.message()}"
- e is java.io.IOException ->
- "Network problem: ${e.message ?: "could not reach the API"}. Check your connection."
- else -> "Something went wrong: ${e.message}"
-}
+internal fun friendlyAgentError(e: Exception): String = HumanReadableError.format(e)
/**
* The core agent loop, extracted from ChatViewModel so it can run both inside
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 608304a..480da66 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -28,6 +28,7 @@ import com.gotcha.marketing.ShareCardClient
import com.gotcha.tools.AgentMode
import com.gotcha.tools.ScreenPerception
import com.gotcha.ui.ConfirmationOverlay
+import com.gotcha.util.HumanReadableError
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
@@ -649,7 +650,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
transcript = sttEngine.transcribeApi(
audioFile, settings.sttApiModel, sttLanguage
)
- .onFailure { e -> appendUi(MessageKind.ERROR, "Transcription failed: ${e.message}") }
+ .onFailure { e ->
+ appendUi(MessageKind.ERROR, "Transcription failed: ${HumanReadableError.format(e)}")
+ }
.getOrDefault("")
}
provider == AudioProvider.ANDROID -> {
diff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.kt
index 580fb11..f0ffe0e 100644
--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt
+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt
@@ -12,6 +12,7 @@ import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.util.Log
import com.gotcha.i18n.Language
+import com.gotcha.util.HumanReadableError
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -182,7 +183,8 @@ class SttEngine(
override fun onBufferReceived(buffer: ByteArray?) {}
override fun onEndOfSpeech() { Log.d(TAG, "onEndOfSpeech") }
override fun onError(error: Int) {
- Log.d(TAG, "onError: $error")
+ val humanMsg = HumanReadableError.fromSpeechRecognizerCode(error)
+ Log.d(TAG, "onError: $error ($humanMsg)")
if (error == SpeechRecognizer.ERROR_CLIENT ||
error == SpeechRecognizer.ERROR_RECOGNIZER_BUSY ||
error == SpeechRecognizer.ERROR_SERVER
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
index c9aa2ce..ec7fb0c 100644
--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
@@ -19,6 +19,7 @@ import com.gotcha.data.SettingsRepository
import com.gotcha.i18n.Language
import com.gotcha.ui.AssistiveBallOverlay
import com.gotcha.ui.CallChatWindow
+import com.gotcha.util.HumanReadableError
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -251,7 +252,7 @@ class AssistiveBallService : Service() {
)
screenCompanionPanel.updateResponse(replyText)
} catch (e: Exception) {
- screenCompanionPanel.updateResponse("Error: ${e.message}")
+ screenCompanionPanel.updateResponse("Error: ${HumanReadableError.format(e)}")
}
}
}
@@ -302,7 +303,7 @@ class AssistiveBallService : Service() {
)
screenCompanionPanel.updateResponse(replyText)
} catch (e: Exception) {
- screenCompanionPanel.updateResponse("Error: ${e.message}")
+ screenCompanionPanel.updateResponse("Error: ${HumanReadableError.format(e)}")
}
}
}
@@ -511,7 +512,7 @@ class AssistiveBallService : Service() {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
} catch (e: Exception) {
- overlay.showError("Couldn't open action: ${e.message}")
+ overlay.showError("Couldn't open action: ${HumanReadableError.format(e)}")
}
}
@@ -567,7 +568,7 @@ class AssistiveBallService : Service() {
)
screenCompanionPanel.updateResponse(replyText)
} catch (e: Exception) {
- screenCompanionPanel.updateResponse("Error: ${e.message}")
+ screenCompanionPanel.updateResponse("Error: ${HumanReadableError.format(e)}")
}
}
}
@@ -594,7 +595,7 @@ class AssistiveBallService : Service() {
showToast("Copied to clipboard")
}
} catch (e: Exception) {
- showToast("Couldn't read text: ${e.message}")
+ showToast("Couldn't read text: ${HumanReadableError.format(e)}")
} finally {
if (!bitmap.isRecycled) bitmap.recycle()
}
@@ -681,7 +682,7 @@ class AssistiveBallService : Service() {
)
updateResponse(replyText)
} catch (e: Exception) {
- updateResponse("Error: ${e.message}")
+ updateResponse("Error: ${HumanReadableError.format(e)}")
}
}
}
@@ -760,7 +761,7 @@ class AssistiveBallService : Service() {
screenCompanionPanel.setListening(false)
result
.onSuccess { text -> if (text.isNotBlank()) screenCompanionPanel.appendVoiceInput(text) }
- .onFailure { e -> overlay.showError("Transcription failed: ${e.message}") }
+ .onFailure { e -> overlay.showError("Transcription failed: ${HumanReadableError.format(e)}") }
}
}
@@ -882,7 +883,7 @@ class AssistiveBallService : Service() {
overlay.showChromeAfterCapture()
chatWindow.setVisibleForCapture(true)
screenCompanionPanel.setVisibleForCapture(true)
- overlay.showError("Screenshot error: ${e.message}")
+ overlay.showError("Screenshot error: ${HumanReadableError.format(e)}")
}
}
}
diff --git a/app/src/main/java/com/gotcha/util/HumanReadableError.kt b/app/src/main/java/com/gotcha/util/HumanReadableError.kt
new file mode 100644
index 0000000..1e10cbc
--- /dev/null
+++ b/app/src/main/java/com/gotcha/util/HumanReadableError.kt
@@ -0,0 +1,100 @@
+package com.gotcha.util
+
+import android.speech.SpeechRecognizer
+import android.speech.tts.TextToSpeech
+import retrofit2.HttpException
+import java.io.IOException
+import java.net.ConnectException
+import java.net.SocketTimeoutException
+import java.net.UnknownHostException
+
+/**
+ * Centralized translator for raw error codes, HTTP statuses, and subsystem exceptions
+ * into clear, user-understandable explanations.
+ */
+object HumanReadableError {
+
+ /** Maps HTTP status codes to human-readable explanations. */
+ fun fromHttpCode(code: Int, rawMessage: String? = null): String = when (code) {
+ 400 -> "Bad request (HTTP 400). The request format or parameters sent to the API were invalid."
+ 401 -> "Authentication failed (HTTP 401). Please check your API key in Settings."
+ 403 -> "Access forbidden (HTTP 403). Your API key does not have permission for this resource or model."
+ 404 -> "Resource not found (HTTP 404). Check if the selected model ID or endpoint URL is correct in Settings."
+ 408 -> "Request timeout (HTTP 408). The server timed out waiting for the request."
+ 429 -> "Rate limit or quota exceeded (HTTP 429). Please wait a moment or check your API usage limits."
+ 500 -> "Server error (HTTP 500). The remote AI service encountered an internal error. Please try again."
+ 502 -> "Bad gateway (HTTP 502). The proxy or upstream service received an invalid response."
+ 503 -> "Service unavailable (HTTP 503). The remote AI service is temporarily down or overloaded."
+ 504 -> "Gateway timeout (HTTP 504). The upstream AI service took too long to respond."
+ else -> {
+ val suffix = if (!rawMessage.isNullOrBlank()) " ($rawMessage)" else ""
+ "The API returned an error (HTTP $code)$suffix."
+ }
+ }
+
+ /** Maps Android [SpeechRecognizer] integer error codes (1–13) to clear explanations. */
+ fun fromSpeechRecognizerCode(code: Int): String = when (code) {
+ SpeechRecognizer.ERROR_NETWORK_TIMEOUT ->
+ "Network connection timed out while recognizing speech."
+ SpeechRecognizer.ERROR_NETWORK ->
+ "Network connection error during speech recognition. Check your internet connection."
+ SpeechRecognizer.ERROR_AUDIO ->
+ "Microphone hardware error. Ensure your microphone is not in use by another app."
+ SpeechRecognizer.ERROR_SERVER ->
+ "Device speech recognition server error. Please try again."
+ SpeechRecognizer.ERROR_CLIENT ->
+ "Android speech recognition client error."
+ SpeechRecognizer.ERROR_SPEECH_TIMEOUT ->
+ "No speech detected. Please speak closer to the microphone."
+ SpeechRecognizer.ERROR_NO_MATCH ->
+ "Could not understand speech. Please try speaking clearer or closer to the mic."
+ SpeechRecognizer.ERROR_RECOGNIZER_BUSY ->
+ "Speech recognizer is busy. Please wait a moment and try again."
+ SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS ->
+ "Microphone permission is required for voice input."
+ SpeechRecognizer.ERROR_TOO_MANY_REQUESTS ->
+ "Too many speech recognition requests sent. Please wait a moment."
+ SpeechRecognizer.ERROR_SERVER_DISCONNECTED ->
+ "Speech recognition service disconnected. Reconnecting..."
+ SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED ->
+ "Selected language is not supported by device speech recognition."
+ SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE ->
+ "Language pack for selected language is not installed on your device."
+ else -> "Speech recognition error (code $code)."
+ }
+
+ /** Maps Android [TextToSpeech] status codes to human-readable explanations. */
+ fun fromTtsCode(code: Int): String = when (code) {
+ TextToSpeech.ERROR_SYNTHESIS -> "Speech synthesis error while generating audio."
+ TextToSpeech.ERROR_SERVICE -> "Android TextToSpeech engine service error."
+ TextToSpeech.ERROR_OUTPUT -> "Audio output stream error during speech playback."
+ TextToSpeech.ERROR_NETWORK -> "Network failure during online speech synthesis."
+ TextToSpeech.ERROR_NETWORK_TIMEOUT -> "Network timeout during speech synthesis."
+ TextToSpeech.ERROR_INVALID_REQUEST -> "Invalid text input or parameters passed to TTS engine."
+ TextToSpeech.ERROR_NOT_INSTALLED_YET -> "TTS voice data is still downloading on your device."
+ else -> "Text-to-speech error (code $code)."
+ }
+
+ /** Translates any exception into a user-friendly error message. */
+ fun format(e: Throwable): String = when {
+ e is HttpException -> fromHttpCode(e.code(), e.message())
+ e is UnknownHostException ->
+ "Cannot connect to server. Check your internet connection or server URL in Settings."
+ e is ConnectException ->
+ "Connection refused by server. Ensure the server is running and accessible."
+ e is SocketTimeoutException ->
+ "Connection timed out waiting for server response. Check network speed or try a smaller request."
+ e is IOException && e.message?.contains("HTTP ") == true -> {
+ val codeStr = e.message?.substringAfter("HTTP ")?.substringBefore(":")?.trim()
+ val code = codeStr?.toIntOrNull()
+ if (code != null) fromHttpCode(code, e.message) else "Network problem: ${e.message}"
+ }
+ e is IOException ->
+ "Network problem: ${e.message ?: "could not reach the server"}. Check your connection."
+ e is SecurityException ->
+ "Permission denied: ${e.message ?: "required permission was not granted"}."
+ !e.message.isNullOrBlank() ->
+ "Error: ${e.message}"
+ else -> "An unexpected error occurred (${e.javaClass.simpleName})."
+ }
+}
diff --git a/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt b/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt
new file mode 100644
index 0000000..35268e3
--- /dev/null
+++ b/app/src/test/java/com/gotcha/util/HumanReadableErrorTest.kt
@@ -0,0 +1,115 @@
+package com.gotcha.util
+
+import android.speech.SpeechRecognizer
+import android.speech.tts.TextToSpeech
+import okhttp3.ResponseBody.Companion.toResponseBody
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import retrofit2.HttpException
+import retrofit2.Response
+import java.io.IOException
+import java.net.ConnectException
+import java.net.SocketTimeoutException
+import java.net.UnknownHostException
+
+class HumanReadableErrorTest {
+
+ @Test
+ fun testFromHttpCodeKnownAndFallbackCodes() {
+ assertTrue(HumanReadableError.fromHttpCode(400).contains("Bad request"))
+ assertTrue(HumanReadableError.fromHttpCode(401).contains("Authentication failed"))
+ assertTrue(HumanReadableError.fromHttpCode(403).contains("Access forbidden"))
+ assertTrue(HumanReadableError.fromHttpCode(404).contains("Resource not found"))
+ assertTrue(HumanReadableError.fromHttpCode(408).contains("Request timeout"))
+ assertTrue(HumanReadableError.fromHttpCode(429).contains("Rate limit"))
+ assertTrue(HumanReadableError.fromHttpCode(500).contains("Server error"))
+ assertTrue(HumanReadableError.fromHttpCode(502).contains("Bad gateway"))
+ assertTrue(HumanReadableError.fromHttpCode(503).contains("Service unavailable"))
+ assertTrue(HumanReadableError.fromHttpCode(504).contains("Gateway timeout"))
+
+ val fallback = HumanReadableError.fromHttpCode(418, "I'm a teapot")
+ assertTrue(fallback.contains("HTTP 418"))
+ assertTrue(fallback.contains("I'm a teapot"))
+ }
+
+ @Test
+ fun testFromSpeechRecognizerCodeKnownAndFallbackCodes() {
+ val errTimeout = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_NETWORK_TIMEOUT)
+ assertTrue(errTimeout.contains("timed out"))
+
+ val errNet = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_NETWORK)
+ assertTrue(errNet.contains("Network connection error"))
+
+ val errAudio = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_AUDIO)
+ assertTrue(errAudio.contains("Microphone hardware error"))
+
+ val errServer = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_SERVER)
+ assertTrue(errServer.contains("server error"))
+
+ val errClient = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_CLIENT)
+ assertTrue(errClient.contains("client error"))
+
+ val errSpeechTimeout = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_SPEECH_TIMEOUT)
+ assertTrue(errSpeechTimeout.contains("No speech detected"))
+
+ val errNoMatch = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_NO_MATCH)
+ assertTrue(errNoMatch.contains("Could not understand speech"))
+
+ val errBusy = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_RECOGNIZER_BUSY)
+ assertTrue(errBusy.contains("recognizer is busy"))
+
+ val errPerm = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS)
+ assertTrue(errPerm.contains("Microphone permission"))
+
+ val errRate = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_TOO_MANY_REQUESTS)
+ assertTrue(errRate.contains("Too many speech recognition"))
+
+ val errDisc = HumanReadableError.fromSpeechRecognizerCode(SpeechRecognizer.ERROR_SERVER_DISCONNECTED)
+ assertTrue(errDisc.contains("disconnected"))
+
+ val fallback = HumanReadableError.fromSpeechRecognizerCode(99)
+ assertTrue(fallback.contains("code 99"))
+ }
+
+ @Test
+ fun testFromTtsCodeKnownAndFallbackCodes() {
+ val synthErr = HumanReadableError.fromTtsCode(TextToSpeech.ERROR_SYNTHESIS)
+ assertTrue(synthErr.contains("Speech synthesis error"))
+
+ val svcErr = HumanReadableError.fromTtsCode(TextToSpeech.ERROR_SERVICE)
+ assertTrue(svcErr.contains("service error"))
+
+ val fallback = HumanReadableError.fromTtsCode(99)
+ assertTrue(fallback.contains("code 99"))
+ }
+
+ @Test
+ fun testFormatExceptions() {
+ val httpEx = HttpException(Response.error<String>(401, "".toResponseBody(null)))
+ assertTrue(HumanReadableError.format(httpEx).contains("Authentication failed"))
+
+ val unknownHost = UnknownHostException("api.openai.com")
+ assertTrue(HumanReadableError.format(unknownHost).contains("Cannot connect to server"))
+
+ val connectEx = ConnectException("Failed to connect")
+ assertTrue(HumanReadableError.format(connectEx).contains("Connection refused"))
+
+ val timeout = SocketTimeoutException("Read timed out")
+ assertTrue(HumanReadableError.format(timeout).contains("Connection timed out"))
+
+ val ioWithHttp = IOException("HTTP 429: Too Many Requests")
+ assertTrue(HumanReadableError.format(ioWithHttp).contains("Rate limit"))
+
+ val genericIo = IOException("Disk read failed")
+ assertTrue(HumanReadableError.format(genericIo).contains("Network problem: Disk read failed"))
+
+ val secEx = SecurityException("RECORD_AUDIO missing")
+ assertTrue(HumanReadableError.format(secEx).contains("Permission denied"))
+
+ val genericEx = IllegalStateException("State invalid")
+ assertTrue(HumanReadableError.format(genericEx).contains("Error: State invalid"))
+
+ val emptyEx = RuntimeException("")
+ assertTrue(HumanReadableError.format(emptyEx).contains("An unexpected error occurred"))
+ }
+}