Files
honeyDueKMP/ERROR_HANDLING.md
Trey t 992979f113 wip
2025-11-07 15:26:22 -06:00

2.9 KiB

Error Handling in MyCrib Apps

Both iOS and Android apps now display detailed error messages from the API.

How It Works

Backend (Django)

The Django backend returns errors in a standardized JSON format:

{
  "error": "Error Type",
  "detail": "Detailed error message",
  "status_code": 400,
  "errors": {
    "field_name": ["Field-specific error messages"]
  }
}

Shared Network Layer (Kotlin Multiplatform)

ErrorResponse Model

Located at: composeApp/src/commonMain/kotlin/com/example/mycrib/models/ErrorResponse.kt

Defines the structure of error responses from the API.

ErrorParser

Located at: composeApp/src/commonMain/kotlin/com/example/mycrib/network/ErrorParser.kt

Parses error responses and extracts detailed messages:

  • Primary error detail from the detail field
  • Field-specific errors from the errors field (if present)
  • Fallback to plain text or generic message if parsing fails

Updated API Calls

All TaskApi methods now use ErrorParser to extract detailed error messages:

  • getTasks()
  • getTask()
  • createTask()
  • updateTask()
  • deleteTask()
  • getTasksByResidence()
  • cancelTask()
  • uncancelTask()
  • markInProgress()
  • archiveTask()
  • unarchiveTask()

Android

Android automatically receives parsed error messages through the shared ApiResult.Error class. ViewModels and UI components display these messages to users.

Example:

when (result) {
    is ApiResult.Error -> {
        // result.message contains the detailed error from ErrorParser
        showError(result.message)
    }
}

iOS

iOS receives parsed error messages through the ApiResultError wrapper class from the shared KMM module. ViewModels extract and display these messages.

Example:

if let errorResult = result as? ApiResultError {
    self.errorMessage = errorResult.message // Contains detailed error from ErrorParser
}

Error Message Format

Simple Errors

Invalid task status

Validation Errors with Field Details

Invalid data provided

Details:
• email: This field is required.
• password: Password must be at least 8 characters.

Benefits

  1. User-Friendly: Users see specific error messages instead of generic "Failed to..." messages
  2. Debugging: Developers can quickly identify issues from error messages
  3. Consistent: Both platforms display the same detailed errors
  4. Maintainable: Single source of truth for error parsing in shared code
  5. Backend-Driven: Error messages are controlled by the Django backend

Testing

To test error handling:

  1. Create a task with invalid data
  2. Update a task with missing required fields
  3. Try to perform actions without authentication
  4. Observe the detailed error messages displayed in the UI

Future Improvements

  • Add error codes for programmatic handling
  • Implement retry logic for specific error types
  • Add localization support for error messages