generated from AND-SOPT-ANDROID/and-sopt-android-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a7005a4
commit f704238
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
data/src/main/java/org/sopt/and/data/common/NetworkResultHandler.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package org.sopt.and.data.common | ||
|
||
import org.sopt.and.domain.exception.* | ||
import retrofit2.HttpException | ||
import java.net.ConnectException | ||
import java.net.SocketTimeoutException | ||
import java.net.UnknownHostException | ||
import org.json.JSONObject | ||
import org.json.JSONException | ||
|
||
inline fun <T> execute(block: () -> T): Result<T> = runCatching { | ||
Result.Success(block()) | ||
}.getOrElse { | ||
Result.Error(handleNetworkError(it)) | ||
} | ||
|
||
fun handleNetworkError(e: Throwable): NetworkError { | ||
return when (e) { | ||
is ConnectException -> ConnectError | ||
is SocketTimeoutException -> TimeoutError | ||
is UnknownHostException -> UnknownHostError | ||
is HttpException -> mapHttpError(e) | ||
else -> UnknownError | ||
} | ||
} | ||
|
||
fun mapHttpError(e: HttpException): NetworkError { | ||
return try { | ||
val statusCode = e.code().toString() | ||
val errorBody = e.response()?.errorBody()?.string() | ||
val errorCode = extractErrorCode(errorBody).toString() | ||
HttpCodeError(statusCode, errorCode) | ||
} catch (ex: Exception) { | ||
UnknownError | ||
} | ||
} | ||
|
||
fun extractErrorCode(errorBody: String?): String? { | ||
return try { | ||
errorBody?.let { JSONObject(it).getString("code") } | ||
} catch (e: JSONException) { | ||
null | ||
} | ||
} | ||
|