I am using Retrofit 2.6.0 with coroutines for my web service call. I am getting the API response properly with all response codes (success & error cases). My Issue is when I
An addition to Arthur Matsegor's answer:
In my case API returns to me an error message for bad requests. For this scenario, i need to catch error message on Catch function. I know, writing try/catch to Catch function looks like ugly but it's worked.
private suspend fun handleRequest(requestFunc: suspend () -> T): Result {
return try {
Result.success(requestFunc.invoke())
} catch (httpException: HttpException) {
val errorMessage = getErrorMessageFromGenericResponse(httpException)
if (errorMessage.isNullOrBlank()) {
Result.failure(httpException)
} else {
Result.failure(Throwable(errorMessage))
}
}
}
private fun getErrorMessageFromGenericResponse(httpException: HttpException): String? {
var errorMessage: String? = null
try {
val body = httpException.response()?.errorBody()
val adapter = Gson().getAdapter(GenericResponse::class.java)
val errorParser = adapter.fromJson(body?.string())
errorMessage = errorParser.errorMessage?.get(0)
} catch (e: IOException) {
e.printStackTrace()
} finally {
return errorMessage
}
}