Skip to content

Instantly share code, notes, and snippets.

@leshchenko
Created August 30, 2019 08:33
Show Gist options
  • Save leshchenko/4b9bc24523e1e1061f40ffc452cddfb7 to your computer and use it in GitHub Desktop.
Save leshchenko/4b9bc24523e1e1061f40ffc452cddfb7 to your computer and use it in GitHub Desktop.
NetworkError
import com.google.gson.Gson
import com.swishhoop.util.TLog
import retrofit2.HttpException
import java.io.IOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import kotlin.reflect.KClass
/**
* Created by vtrifonov on 8/29/19.
*/
fun Throwable.toNetworkError(): NetworkError<Nothing>? {
return NetworkError.create(this)
}
fun <T : Any> Throwable.toNetworkError(errorResponseType: KClass<T>?): NetworkError<T>? {
return NetworkError.create(this, errorResponseType)
}
fun Throwable.isNetworkError() = this is HttpException || this is UnknownHostException
|| this is SocketTimeoutException || this is ConnectException
class NetworkError<T>(
val status: Status,
val code: Int,
val message: String?,
val body: T? = null
) {
enum class Status {
NO_NETWORK,
FAILURE,
UNAUTHORIZED,
FORBIDDEN,
BAD_REQUEST,
}
companion object {
fun create(throwable: Throwable): NetworkError<Nothing>? {
return create(throwable, null)
}
fun <T : Any> create(throwable: Throwable, errorResponseType: KClass<T>?): NetworkError<T>? {
if (!throwable.isNetworkError()) {
return null
}
return if (throwable is HttpException) {
val errorBody = errorResponseType?.let {
getErrorBodyAs(it, throwable)
}
when (val code = throwable.code()) {
400 -> NetworkError(Status.FAILURE, code, throwable.message, errorBody)
401 -> NetworkError(Status.UNAUTHORIZED, code, throwable.message, errorBody)
403 -> NetworkError(Status.FORBIDDEN, code, throwable.message, errorBody)
else -> NetworkError(Status.BAD_REQUEST, code, throwable.message, errorBody)
}
} else {
NetworkError(Status.NO_NETWORK, 0, "No internet connection.")
}
}
private fun <T : Any> getErrorBodyAs(type: KClass<T>, error: HttpException?): T? {
var errorObject: T? = null
error?.response()?.errorBody()?.let {
try {
errorObject = Gson().fromJson(it.string(), type.java)
} catch (e: IOException) {
TLog.i(e, e.localizedMessage)
}
}
return errorObject
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment