Kotlin Android Retrofit 2.6.0 with coroutines error handling

后端 未结 7 2040
粉色の甜心
粉色の甜心 2021-01-30 23:09

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

7条回答
  •  梦毁少年i
    2021-01-30 23:45

    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
        }
    }
    

提交回复
热议问题