Home > Mobile >  How to receive body of error message with retrofit and kotlin?
How to receive body of error message with retrofit and kotlin?

Time:12-13

I am trying to get the error of the body. I have a code, but it fails in try block and goes directly to catch block. So i receive http 400 error, but i need to receive a more specific error from the server. How can i improve my code to get it?

 try { 
    api.uploadImage(imgId, requestBody).enqueue(object : Callback<Void> {
    override fun onResponse(call: Call<Void>, response: Response<Void>) {
        if (!response.isSuccessful()) {
            val errorBody = response.errorBody()?.string()
           
        }
    }

    override fun onFailure(call: Call<Void>, t: Throwable) {
        Log.i("tag", "uploadImage: ${t.message}")
    }
})} catch (e: Exception) {
     Log.i("tag", "uploadImage: ${e.message}")
}

CodePudding user response:

You should debug your catch block to identify error type, then you can catch it and get message from specific error class

CodePudding user response:

Maybe like this:

object ErrorUtils {

fun parseError(response: Response<*>): APIError {
    val converter = ServiceGenerator.retrofit()
            .responseBodyConverter(APIError::class.java, arrayOfNulls<Annotation>(0))

    val error: APIError

    try {
        error = converter.convert(response.errorBody())
    } catch (e: IOException) {
        return APIError()
    }

    return error
}

}

Then could use it like

        APIError error = ErrorUtils.parseError(response);
        Log.d("error message", error.message());
  • Related