Search code examples
androidkotlinretrofitokhttp

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


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

Solution

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