Kaaveh / ComposeNews

A playground about best practices, using updated libraries and solutions in the Android world!
Apache License 2.0
325 stars 53 forks source link

Enhance/error handling #219

Closed mhmd-android closed 2 months ago

mhmd-android commented 2 months ago

Error Handling Improvement

Hi, I'm back with a new PR :). This PR primarily aims to enhance error handling across the project, but it also introduces significant improvements and refactoring to the overall code structure.

One of the most significant improvements in this PR is the introduction of a robust and flexible API response handling system using Ktor. This new system provides a more structured and type-safe way to manage API responses and errors.

Key Components:

1. ApiResponse Sealed Interface:

2. apiResponseOf Function:

3. Extension Functions for HttpResponse:

4. HttpClient Extensions:

5. ApiResponse Extension Functions:

6. Error Handling:

Benefits of This Approach:

  1. Type Safety: The sealed interface ensures that all possible response types are handled.
  2. Separation of Concerns: Clearly separates successful responses, API errors, and exceptions.
  3. Flexibility: The extension functions allow for easy chaining of response handling logic.
  4. Coroutine Support: Designed to work seamlessly with Kotlin coroutines.
  5. Improved Error Handling: Provides detailed information about different types of failures.

One of Usage Example::

client.getApiResponse<UserData> {
    url("https://api.example.com/user")
}.onSuccess { 
    // Handle successful response
}.onError { 
    // Handle API errors
}.onException {
    // Handle exceptions
}

This new system replaces the previous approach of handling Ktor responses with individual functions, providing a more cohesive and maintainable solution. It significantly improves error handling capabilities and makes API interactions more predictable and easier to manage throughout the application.

Important Note:

Thank you for your review and feedback.

205

Kaaveh commented 2 months ago

@VahidGarousi are we ready to merge the PR?