Search code examples
androidkotlinmvvmretrofit2kotlin-coroutines

How to handle error response return from server api in kotlin+retrofit+coroutine+mvvm


I have two different response from the same endpoint. One being the actual success result data model and one being an error response model. Both json structure like this:

SuccessResponse:

{
   "result":{
      "id":1,
      "name_en":"Stack Over Flow",
      "summary":"Stack Overflow is the largest, most trusted online community for developers to learn, share​ ​their programming ​knowledge, and build their careers."
   }
}

ErrorResponse:

{
    "message": "Login Failed"
}

I can handle the success response but I can't show the error message what I get from the server. I have tried many ways but I can't do this. Here my I share my some aspect what I did

MainViewModel.kt

var job: Job? = null
val myDataResponse: MutableLiveData<HandleResource<DataResponse>> =MutableLiveData()

fun myData() {
        job = CoroutineScope(Dispatchers.IO).launch {

            val myDataList = mainRepository.myData()

            withContext(Dispatchers.Main) {
                myDataResponse.postValue(handleMyDataResponse(myDataList))
            }

        }

    }
private fun handleMyDataResponse(myDataResponse: Response<DataResponse>): HandleResource<DataResponse>? {
        if (myDataResponse.isSuccessful) {

            myDataResponse.body()?.let { myDataData ->
                return HandleResource.Success(myDataData)
            }

        }

        return HandleResource.Error(myDataResponse.message())
    }

I need a solution while server give me error message I want to show same error message on my front side. How can I achieve this?


Solution

  • private fun handleMyDataResponse(myDataResponse: Response<DataResponse>): HandleResource<DataResponse>? {
          
          myDataResponse.body()?.let { myDataData ->    
             if (myDataResponse.code() == 200) {                     
               return HandleResource.Success(myDataData )                 
             } else {
               val rawResponse = myDataData.string()                        
               return HandleResource.Error(getErrorMessage(rawResponse))     
             } 
          }
        }
    
    
    fun getErrorMessage(raw: String): String{   
      val object = JSONObject(raw);
      return object.getString("message");
    }
    

    The body of the response (be it success or failure) is response.body(). And if you want to get it as a String, then call response.body().string(). Since you want to read message object from the response you need to convert it into Json.