Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gab-stargazer/86309033ffba84a707e4beb39abb98f5 to your computer and use it in GitHub Desktop.
Save gab-stargazer/86309033ffba84a707e4beb39abb98f5 to your computer and use it in GitHub Desktop.
This function is for parsing Error Response from Json by using custom class for deserialization for specific error response by using custom class for deserialization JSON. Replace ErrorResponse::class.java with your own custom class. One thing to note is JSON can only be used once, so if you want to reuse it then store the JSON on a variable.
private fun parseHttpError(t: HttpException): String {
val body = t.response()?.errorBody()
val gson = Gson()
val adapter: TypeAdapter<ErrorResponse> = gson.getAdapter(ErrorResponse::class.java)
return try {
val error = adapter.fromJson(body?.string())
"Error ${error.status}: ${error.message}"
} catch (e: Exception) {
"Response failed to parse"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment