Last active
January 23, 2023 14:44
-
-
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.
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
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