Boris
Boris

Reputation: 223

Retrofit 2 handle dynamic errors

i am using retrofit 2 where i am sending request to a rest server. I am having issues with parsing the error resposne from the server. As an example i am showing the register api call.

One i hit this endpoint with a email which is not present in the server db i am getting the following reposne :

{
    "id": "90c51a63-9a5d-46ee-9da6-7227f7042373",
    "email": "[email protected]",
    "username": "TOdor",
    "phoneNumber": null,
    "phoneNumberIsVerified": false,
    "isIdenfyVerified": false
}

I am able to parse the above json to Java object. The issue comes if i want to catch the error like if i use the same email the backend returns a 400 status with message that the email already exist as there was already a user registered with that same email. Below you can find how the json looks, my question is how can i parse this reponse.

  {
      "Message": "One or more validation failures have occurred.",
      "Failures": {
          "Email": [
             "Email already exists."
          ]
       }
  }

PS: keep in mind that the email object can change based on different errors from the server. Is there a way to handle this elegantly.

Kind regards

Upvotes: 0

Views: 722

Answers (2)

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 15423

Create a model to handle your custom error

class CustomError {
    String Message;
    List<String> Failures;

    ...

    //getter and setter
}

Then using Retrofit responseBodyConverter parse your error model like below:

public CustomError getCustomError(ResponseBody responseBody) {
    CustomError customError;

    Converter converter = retrofit.responseBodyConverter(CustomError.class, new Annotation[] {});

    try {
        customError = (CustomError) converter.convert(responseBody);
    } catch (Exception ex) {
        customError = null;
    }

    return customError;
}

And try to change your response like below to handle it dynamically

{
    "Message": "One or more validation failures have occurred.",
    "Failures": [
        "Email already exists.",
        "Invalid phone number",
        "Username not found"
    ]
}

Upvotes: 0

Divyanshu
Divyanshu

Reputation: 462

you can get error response by this onResposne()

try {
  JSONObject jObjError = new JSONObject(response.errorBody().string());
  Log.e("Error ", "response : " + jObjError);
} catch (JSONException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

and you can check api status code by

response.code()

Upvotes: 1

Related Questions