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
detailfield - Field-specific errors from the
errorsfield (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
- User-Friendly: Users see specific error messages instead of generic "Failed to..." messages
- Debugging: Developers can quickly identify issues from error messages
- Consistent: Both platforms display the same detailed errors
- Maintainable: Single source of truth for error parsing in shared code
- Backend-Driven: Error messages are controlled by the Django backend
Testing
To test error handling:
- Create a task with invalid data
- Update a task with missing required fields
- Try to perform actions without authentication
- 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