Home > front end >  Retrofit Error Handling with different types of responses
Retrofit Error Handling with different types of responses

Time:11-09

I have two different responses for two different scenarios. One scenario is that I get a JSONArray as a response

 [ {
        "type" : "cat",       
        "color": "black"
      }, 
      {
        "type" : "cat",
        "color": "white"
      } ]

this is the normal response that I am supposed to get. But If the response isnt available for the body that I am sending, I get the following response.

{ "message" : "response not available for this date" }

this is the post request that I have

@POST("user/userTimetable")
    fun getTypeApi(@HeaderMap headers: Map<String, String>, @Body body: ScheduleBody?) : Call <List<Type>>

When I get the latter response, I am getting a crash

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

How do I work with this type of response on kotlin?

CodePudding user response:

Retrofit won't predict the response, so either you set the result type to ResponseBody with an object type or change your backend to send a default case that implements the error message and the data.

CodePudding user response:

I once had this issue, please follow the code below

  1. create a model class called ErrorResponse which will return the Data above and modify to show only your message response.

enter image description here

  1. create a class called ErrorResponseService which will be used to map the ErrorMessage to the returning respose.

enter image description here

  1. Then do this implementation in your Retrofit call to get the error message when your response fails.

enter image description here

  • Related