Search code examples
androidandroid-studioobservableretrofit2rx-java2

retrofit2 rxjava 2 - how can access to body of response when have error


I use Retrofit with Rxjava together for request to server.
the my server return defined json format that Include data , and defined message.
server return http response. it's ok if server return success code(200).
but I want, if server return other code, i manage the body of that response.
for example:
the server return 401, and I want read body of response for show message of the server.
but when server other code, retrofit call the onError method and I can't use body of response.
how can solve this problem?
this is my mehod

'''

private void login(String username , String password){
    view.setLoading();
    source.loginUser(username, password)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SingleObserver<Response<LoginResult>>() {
                @Override
                public void onSubscribe(Disposable d) {
                    disposable.add(d);
                }

                @Override
                public void onSuccess(Response<LoginResult> loginResult) {

                    if (loginResult.isSuccessful()){


                        }
                        else
         new AlertConfiguration(view.getViewActivity()).showMessage(loginResult.body().getMessage());

                    }



                @Override
                public void onError(Throwable e) {

           if there is a problem          
                }
            });

'''
and this is my interface method for retrofit

@POST("...")
Single<Response<LoginResult>> loginUser(@Query("username") String username, @Query("password") String password);

Solution

  • I find solution
    in retrofit onSuccess methode when response code is 200, you should get response from body object.
    but when isn't 200, you should get response from errorBody;

    new Gson().fromJson(serverResultResponse.errorBody().string(), ServerResult.class);