Created
October 28, 2019 08:41
-
-
Save julianfalcionelli/8ce1b2b6289d51ae87fc4c6f8a208bda to your computer and use it in GitHub Desktop.
ServerException Kotlin Version
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
import retrofit2.Response | |
import retrofit2.Retrofit | |
import timber.log.Timber | |
import java.io.IOException | |
class ServerException internal constructor( | |
message: String?, | |
/** | |
* The request URL which produced the error. | |
*/ | |
val url: String?, | |
/** | |
* Response object containing status code, headers, body, etc. | |
*/ | |
val response: Response<*>?, | |
/** | |
* The event kind which triggered this error. | |
*/ | |
val kind: Kind, | |
exception: Throwable?, | |
/** | |
* The Retrofit this request was executed on. | |
*/ | |
private val retrofit: Retrofit? | |
) : RuntimeException(message, exception) { | |
public var serverError: SilenceServerError? = null | |
/** | |
* Identifies the event kind which triggered a [ServerException]. | |
*/ | |
enum class Kind { | |
/** | |
* An [IOException] occurred while communicating to the server. | |
*/ | |
NETWORK, | |
/** | |
* A non-200 HTTP status code was received from the server. | |
*/ | |
HTTP, | |
/** | |
* An internal error occurred while attempting to execute a request. It is best practice to | |
* re-throw this exception so your application crashes. | |
*/ | |
UNEXPECTED | |
} | |
init { | |
if (response != null) { | |
try { | |
serverError = getErrorBodyAs(SilenceServerError::class.java) | |
} catch (exception: IOException) { | |
Timber.d(exception) | |
} | |
} | |
} | |
/** | |
* HTTP response body converted to specified `type`. `null` if there is no | |
* response. | |
* | |
* @throws IOException if unable to convert the body to the specified `type`. | |
*/ | |
@Throws(IOException::class) | |
fun <T> getErrorBodyAs(type: Class<T>): T? { | |
if (response?.errorBody() == null) { | |
return null | |
} | |
val converter = retrofit?.responseBodyConverter<T>(type, | |
arrayOfNulls(0)) | |
return converter?.convert(response.errorBody()!!) | |
} | |
companion object { | |
fun httpError(url: String, response: Response<*>, retrofit: Retrofit): ServerException { | |
val message = response.code().toString() + " " + response.message() | |
return ServerException(message, url, response, Kind.HTTP, null, retrofit) | |
} | |
fun networkError(exception: IOException): ServerException { | |
return ServerException(exception.message, null, null, Kind.NETWORK, exception, null) | |
} | |
fun unexpectedError(exception: Throwable): ServerException { | |
return ServerException(exception.message, null, null, Kind.UNEXPECTED, exception, null) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment