Skip to content

Commit

Permalink
refactor: improve error handling in safeApiCall
Browse files Browse the repository at this point in the history
This commit improves error handling in the `safeApiCall` function:

- Handles `HttpException` specifically
 to provide more informative error messages based on HTTP status codes (401, 403, 404).
- Removes unnecessary empty block in `Resource.Loading`.
- Adds logging of access and refresh tokens in `TokenManager`.
  • Loading branch information
OkelloSam21 committed Aug 15, 2024
1 parent 236bc14 commit e026e12
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 9 deletions.
4 changes: 1 addition & 3 deletions app/src/main/java/com/samuelokello/kazihub/utils/Resource.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,5 @@ package com.samuelokello.kazihub.utils
sealed class Resource <T>(val data: T? = null, val message: String? = null) {
class Success<T>(data: T) : Resource<T>(data)
class Error<T>(message: String, data: T? = null) : Resource<T>(data, message)
class Loading<T> : Resource<T>() {

}
class Loading<T> : Resource<T>()
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.samuelokello.kazihub.utils

import android.util.Log
import javax.inject.Inject

// TokenManager.kt
Expand All @@ -10,6 +11,8 @@ class TokenManager @Inject constructor() {
fun setToken(access: String, refresh: String) {
accessToken = access
refreshToken = refresh
Log.d("TokenManager", "Access Token: $accessToken")
Log.d("TokenManager", "Refresh Token: $refreshToken")
}

fun getAccessToken(): String = accessToken
Expand Down
20 changes: 14 additions & 6 deletions app/src/main/java/com/samuelokello/kazihub/utils/safeApiCall.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,21 @@ package com.samuelokello.kazihub.utils

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.HttpException

suspend fun <T> safeApiCall(apiCall: suspend () -> T): Resource<T> {
return withContext(Dispatchers.IO) {
try {
Resource.Success(apiCall.invoke())
} catch (throwable: Throwable) {
Resource.Error(throwable.localizedMessage ?: "An unexpected error occurred")
return withContext(Dispatchers.IO) {
try {
Resource.Success(apiCall.invoke())
} catch (throwable: HttpException) {
when (throwable.code()) {
401 -> Resource.Error("Unauthorized. Please log in again.")
403 -> Resource.Error("Forbidden. You don't have permission to access this resource.")
404 -> Resource.Error("Resource not found.")
else -> Resource.Error("An error occurred: ${throwable.message()}")
}
} catch (throwable: Throwable) {
Resource.Error(throwable.localizedMessage ?: "An unexpected error occurred")
}
}
}
}

0 comments on commit e026e12

Please sign in to comment.