> ## Documentation Index
> Fetch the complete documentation index at: https://docs.runanywhere.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Error Handling

> Handle SDK errors gracefully

## SDKError

All SDK operations throw `SDKError` for error conditions:

```kotlin theme={null}
data class SDKError(
    val code: ErrorCode,           // Specific error type
    val category: ErrorCategory,   // Error group
    val message: String,           // Human-readable message
    val cause: Throwable?          // Underlying exception
) : Exception(message, cause)
```

## Basic Error Handling

```kotlin theme={null}
try {
    RunAnywhere.loadLLMModel("my-model")
    val result = RunAnywhere.generate("Hello")

} catch (e: SDKError) {
    when (e.code) {
        ErrorCode.NOT_INITIALIZED -> {
            showError("Please restart the app")
        }
        ErrorCode.MODEL_NOT_FOUND -> {
            showError("Model not found. Please download it first.")
        }
        ErrorCode.MODEL_LOAD_FAILED -> {
            showError("Failed to load model: ${e.message}")
        }
        ErrorCode.LLM_GENERATION_FAILED -> {
            showError("Generation failed: ${e.message}")
        }
        ErrorCode.INSUFFICIENT_STORAGE -> {
            showError("Not enough storage space")
        }
        else -> {
            showError(e.message ?: "Unknown error")
        }
    }
}
```

## Error Categories

Handle errors by category for broader matching:

```kotlin theme={null}
try {
    // SDK operations...
} catch (e: SDKError) {
    when (e.category) {
        ErrorCategory.INITIALIZATION -> {
            // SDK not properly initialized
            restartApp()
        }
        ErrorCategory.MODEL -> {
            // Model-related issues
            promptModelDownload()
        }
        ErrorCategory.LLM -> {
            // Text generation errors
            retryWithSmallerPrompt()
        }
        ErrorCategory.STT -> {
            // Speech recognition errors
            checkMicrophonePermission()
        }
        ErrorCategory.TTS -> {
            // Speech synthesis errors
            checkAudioOutput()
        }
        ErrorCategory.NETWORK -> {
            // Network connectivity issues
            showOfflineMessage()
        }
        ErrorCategory.STORAGE -> {
            // Storage/file system errors
            promptStorageCleanup()
        }
        else -> {
            logError(e)
            showGenericError()
        }
    }
}
```

## Error Categories Reference

| Category         | Description      | Common Errors                            |
| ---------------- | ---------------- | ---------------------------------------- |
| `INITIALIZATION` | SDK startup      | `NOT_INITIALIZED`, `ALREADY_INITIALIZED` |
| `MODEL`          | Model operations | `MODEL_NOT_FOUND`, `MODEL_LOAD_FAILED`   |
| `LLM`            | Text generation  | `LLM_GENERATION_FAILED`                  |
| `STT`            | Speech-to-text   | `STT_TRANSCRIPTION_FAILED`               |
| `TTS`            | Text-to-speech   | `TTS_SYNTHESIS_FAILED`                   |
| `VAD`            | Voice detection  | `VAD_DETECTION_FAILED`                   |
| `NETWORK`        | Network issues   | `NETWORK_UNAVAILABLE`, `TIMEOUT`         |
| `DOWNLOAD`       | Model downloads  | `DOWNLOAD_FAILED`, `DOWNLOAD_CANCELLED`  |
| `STORAGE`        | Storage issues   | `INSUFFICIENT_STORAGE`, `FILE_NOT_FOUND` |

## Common Error Codes

```kotlin theme={null}
enum class ErrorCode {
    // General
    SUCCESS,
    UNKNOWN,
    INVALID_ARGUMENT,

    // Initialization
    NOT_INITIALIZED,
    ALREADY_INITIALIZED,

    // Model
    MODEL_NOT_FOUND,
    MODEL_NOT_LOADED,
    MODEL_LOAD_FAILED,

    // LLM
    LLM_GENERATION_FAILED,

    // STT
    STT_TRANSCRIPTION_FAILED,

    // TTS
    TTS_SYNTHESIS_FAILED,

    // VAD
    VAD_DETECTION_FAILED,

    // Network
    NETWORK_ERROR,
    NETWORK_UNAVAILABLE,
    TIMEOUT,

    // Download
    DOWNLOAD_FAILED,
    DOWNLOAD_CANCELLED,

    // Storage
    INSUFFICIENT_STORAGE,
    FILE_NOT_FOUND,
    OUT_OF_MEMORY
}
```

## Error Factory Methods

Create specific errors programmatically:

```kotlin theme={null}
// These are used internally by the SDK
SDKError.modelNotFound(modelId)
SDKError.modelNotLoaded(modelId)
SDKError.modelLoadFailed(modelId, reason)
SDKError.llmGenerationFailed(reason)
SDKError.sttTranscriptionFailed(reason)
SDKError.ttsSynthesisFailed(reason)
SDKError.networkUnavailable()
SDKError.timeout(operation, timeoutMs)
SDKError.insufficientStorage(requiredBytes)
SDKError.fileNotFound(path)
```

## Example: Comprehensive Error Handler

```kotlin theme={null}
class SDKErrorHandler {

    fun handle(error: SDKError, context: Context) {
        Log.e("SDK", "Error: ${error.code} - ${error.message}", error.cause)

        val userMessage = when (error.code) {
            // Initialization errors
            ErrorCode.NOT_INITIALIZED ->
                "The AI system isn't ready yet. Please wait or restart the app."

            // Model errors
            ErrorCode.MODEL_NOT_FOUND ->
                "This model isn't available. Please download it first."
            ErrorCode.MODEL_LOAD_FAILED ->
                "Couldn't load the AI model. Try freeing up some memory."

            // Generation errors
            ErrorCode.LLM_GENERATION_FAILED ->
                "Couldn't generate a response. Please try again."
            ErrorCode.STT_TRANSCRIPTION_FAILED ->
                "Couldn't understand the audio. Please speak clearly."
            ErrorCode.TTS_SYNTHESIS_FAILED ->
                "Couldn't create audio. Please try again."

            // Network errors
            ErrorCode.NETWORK_UNAVAILABLE ->
                "No internet connection. Some features may be limited."
            ErrorCode.TIMEOUT ->
                "Request took too long. Please try again."

            // Download errors
            ErrorCode.DOWNLOAD_FAILED ->
                "Download failed. Please check your connection and try again."
            ErrorCode.DOWNLOAD_CANCELLED ->
                "Download was cancelled."

            // Storage errors
            ErrorCode.INSUFFICIENT_STORAGE ->
                "Not enough storage space. Free up some space and try again."
            ErrorCode.OUT_OF_MEMORY ->
                "Not enough memory. Try closing other apps."

            else ->
                "Something went wrong. Please try again."
        }

        Toast.makeText(context, userMessage, Toast.LENGTH_LONG).show()
    }
}
```

## Subscribe to Error Events

```kotlin theme={null}
lifecycleScope.launch {
    RunAnywhere.events.errorEvents.collect { errorEvent ->
        Log.e("SDK", "Error event: ${errorEvent.code} - ${errorEvent.message}")
        // Handle or report error
    }
}
```
