@@ -5,37 +5,47 @@ import com.google.gson.JsonParseException
55import retrofit2.HttpException
66import retrofit2.Response
77import java.io.IOException
8+ import java.net.HttpURLConnection
89import java.util.concurrent.TimeoutException
910
1011// Safe API call handler with suspend
1112suspend fun <T > safeApiCall (apiCall : suspend () -> Response <T >): ResultHandler <T > {
1213 return try {
1314 val response = apiCall()
14- when {
15- response.isSuccessful -> {
16- response.body()?.let { ResultHandler .Success (it) }
17- ? : ResultHandler .Error (
18- message = " HTTP 200: Empty response body" ,
19- remoteApiError = RemoteApiError .EMPTY_BODY
20- )
21- }
15+ val body = response.body()
2216
23- else -> ResultHandler .Error (
17+ if (response.isSuccessful) {
18+ if (body != null ) {
19+ return if (response.code() == HttpURLConnection .HTTP_OK ) {
20+ ResultHandler .Success (body)
21+ } else {
22+ ResultHandler .Partial (body)
23+ }
24+ } else {
25+ ResultHandler .Error (
26+ message = " HTTP ${response.code()} : Empty response body" ,
27+ remoteApiError = RemoteApiError .EMPTY_BODY
28+ )
29+ }
30+ } else {
31+ ResultHandler .Error (
2432 message = " HTTP Error: ${response.code()} - ${response.message()} " ,
2533 remoteApiError = RemoteApiError .UNEXPECTED_ERROR
2634 )
2735 }
2836 } catch (exception: Throwable ) {
29- exception.stackTrace
3037 handleApiError(exception)
3138 }
3239}
3340
3441// Exception handling with detailed Resource.Error
3542private fun <T > handleApiError (exception : Throwable ): ResultHandler <T > {
43+ println (" 🚨 Exception caught in Network Call 🚨" )
44+ exception.printStackTrace()
3645 val remoteApiError = when (exception) {
3746 is TimeoutException -> RemoteApiError .TIMEOUT
3847 is NoConnectivityException -> RemoteApiError .NO_INTERNET
48+ is JsonParseException , is MalformedJsonException -> RemoteApiError .JSON_PARSE
3949 is IOException -> RemoteApiError .IO_ERROR
4050 is HttpException -> {
4151 when (exception.code()) {
@@ -48,8 +58,6 @@ private fun <T> handleApiError(exception: Throwable): ResultHandler<T> {
4858 else -> RemoteApiError .UNEXPECTED_HTTP_ERROR
4959 }
5060 }
51-
52- is JsonParseException , is MalformedJsonException -> RemoteApiError .JSON_PARSE
5361 is IllegalArgumentException -> RemoteApiError .ILLEGAL_ARGUMENT
5462 is IllegalStateException -> RemoteApiError .ILLEGAL_STATE
5563 else -> RemoteApiError .UNEXPECTED_ERROR
@@ -59,8 +67,4 @@ private fun <T> handleApiError(exception: Throwable): ResultHandler<T> {
5967 exception = exception,
6068 remoteApiError = remoteApiError
6169 )
62- }
63-
64- private fun accessDeniedError (): ResultHandler <Nothing > {
65- return ResultHandler .AccessDenied
6670}
0 commit comments