Skip to content

Instantly share code, notes, and snippets.

@julianfalcionelli
Created October 28, 2019 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianfalcionelli/8ce1b2b6289d51ae87fc4c6f8a208bda to your computer and use it in GitHub Desktop.
Save julianfalcionelli/8ce1b2b6289d51ae87fc4c6f8a208bda to your computer and use it in GitHub Desktop.
ServerException Kotlin Version
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