7
votes

I make an api call which returns me this

Response{protocol=http/1.1, code=422, message=Unprocessable Entity, url=https://someapi/endpoint}

In the logs, along with the response i get the following:

{"message":"Validation Failed","errors":{"email":["has already been taken"]}}

I'm working on an Android app that has a profile creation feature and I want to redirect the user back so it can change its email address when I receive this response but for that I need to fetch and handle the "errors" message.

How can i get the message from the error body ? I've tried like this:

response.message()

But I get only

Unprocessable Entity

1
i think you can pass code = 200 - Saif
which client are you using to make network calls? retrofit, volley ?? - Rakesh Godhala
retrofit and rx java as call adapter factory - petryk33
@Saif I don't know what to say to your answer man.... - petryk33
in your response code which code you have to get from the api ? if you have get 422 code from the api, Android are consider as a Exception. - Saif

1 Answers

6
votes

Try like below

 .subscribe(res-> {
                      //success case

                    },
                    t -> {
                        if (t instanceof HttpException) {
                           if (((HttpException) t).code() == 422) {
                           String errorResponse=((HttpException) t).response().errorBody().string();
                         //your validations
                        }
                        } else {

                            t.printStackTrace();

                        }
                    });

I hope it's will help you :-)