How to parse error response to Throwable?

I am using Retrofit and RxJava to make network requests like this:

How I am declaring request:

@POST("auth/profile/edit/")
fun updateProfile(@Body body: ProfileUpdateBody): Single<Response<Void>>

How I am calling:

api.updateProfile(**some data**)
     .subscribeOn(Schedulers.io())
     .observeOn(AndroidSchedulers.mainThread())
     .doOnSubscribe {
          Log.d("----------", "Subscribed!")
     }
     .doOnSuccess {
          if(it.isSuccessful)
              Log.d("----------", "Success!")
          else
              Log.d("----------", "Not Successfull!")
     }
    .doOnError {
          Log.d("----------", "Error Happened!")
            }
    .subscribe({
     }, {

     })

Some code have been dropped for readability. The probem is even though I get responses back with 401 or 400 statuses, doOnSuccess is being called. Should not the doOnError be called here? I am confused.

As a result my logact is showing "Not Successful" message. How can make sure that doOnErro is called when I get responses back with 401 or 400 statuses?

Or can I parse the incoming response to Throwable and call doOnError() function?

Change the Retrofit API call to return Completable:

@POST("auth/profile/edit/")
fun updateProfile(@Body body: ProfileUpdateBody): Completable

then handle the "success case" via doOnComplete:

api.updateProfile(**some data**)
 .subscribeOn(Schedulers.io())
 .observeOn(AndroidSchedulers.mainThread())
 .doOnSubscribe {
      Log.d("----------", "Subscribed!")
 }
 .doOnComplete {
      Log.d("----------", "Success!")
 }
 .doOnError {
      Log.d("----------", "Error Happened!")
 }
 .subscribe({  }, {  })

Retrofit 2.0, onError(e); } } } } @Override public void onFailure(Call<T> call, Throwable t) { if errorBody().string(); // use Gson to parse json to your Error handling model� Throwable Exceptions and Errors in PHP 7 Exploring the exception hierarchy of PHP 7 June 24, 2015

The real question is, why would you want to throw and exception when the request fails?

The correct processes are being followed here, doOnSuccess is being called as intended because the request has returned a response without encountering an exception being thrown. Regardless of whether the request's response is successful or not.

You should handle the state of your response accordingly and not throw arbitrary exceptions for it:

api.updateProfile(**some data**)
     .subscribeOn(Schedulers.io())
     .observeOn(AndroidSchedulers.mainThread())
     .subscribe(response -> {
         if (response.isSuccessful()) {
             // handle success
         } else {
             // handle failure
         }
     }, t -> {
         // handle thrown error
         yourErrorHandlerMethod(t);
     })

How to parse http error body using Retrofit | by Dalvin, If you are using RxJava2 and retrofit provided RxJava2 call adapter to receive observable stream then in case of error you get throwable in your observers onError() method. If this throwable is of HttpException then its message field contains the error body and you have to parse this error body. In this tutorial, I'm going to show you how to parse custom JSON response body in Retrofit 2. Preparation First, we create RetrofitClientInstance class for creating new instance of Retrofit client and the MyService interface which defines the endpoint we're going to call.

The response you getting is correct, the response is shown in doOnSuccess cuz the API you hitting got successfully hit, no matter what was the response code. doOnError is called when actual API call is failed like network drop in the middle or some server-side issues.

Or can I parse the incoming response to Throwable and call doOnError() function?

You cant do this instead, you can handle the response in doOnSuccess as

 try {
 api.updateProfile(**some data**)
 .subscribeOn(Schedulers.io())
 .observeOn(AndroidSchedulers.mainThread())
 .doOnSubscribe {
      Log.d("----------", "Subscribed!")
 }
 .doOnSuccess {
      if(it.isSuccessful) // responce code = 200/201
          Log.d("----------", "Success!")
      else if (it.responseCode == 400 ){
          Log.d("----------", "Not Found!")
          // Call a method that handles this according to your requirement.
          PageNotFoundHandler();
          // OPTIONAL throw new UserException();
        }
      else if (it.responseCode == 401 ){
          Log.d("----------", "Not Authorised!")
          // Call a method that handles this according to your requirement.
          TokenExpiredHandler(); //OR
          UnAuthorizedAccessHandler();
          // OPTIONAL throw new UserException();
        }
      else {
          Log.d("----------", "Some another Error!")
          // Call a method that handles this according to your requirement.
          // OPTIONAL throw new UserException();
        }

 }
.doOnError {
      Log.d("----------", "Error Happened!")
        }
.subscribe({
 }, {

 })
 } catch 
 {
    ErrorHandler();
 }

Or can I parse the incoming response to Throwable and call doOnError() function?

As you mention that you want a throwable, you can achieve it by using the try-catch block.

Just throw a custom EXCEPTION, you have to create a new Custom Exception class for it.

Retrofit 2 — Simple Error Handling, The thing that is required to parse the JSON error is the response public void onFailure(Call<User> call, Throwable t) { // there is more than� Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Retrofit + RxJava, how to obtain the responses' error body in case , I am using retrofit:2.0.0-beta2 with RxJava and i cannot access the response body in errorBody().string(); // now,you can do what you want to do ,like parse .. .. } body from API in case of an error as onError method only takes in a Throwable. To fix parse error, you can take some useful steps. This article will explain everything clearly. This article will explain everything clearly. Android is the most popular operating system for the mobile platform.

Retrofit parse error body sample � GitHub, Retrofit parse error body sample. Log.d(TAG, "onResponse() called with: call = [" + call + "], response = [" + errorModel = converter.convert(response. public void onFailure(@NonNull Call<ExpectedModel> call, @NonNull Throwable t) {. The responseConverter method will return the appropriate converter to parse the response body type. In our case, we’re expecting a JSON converter, because we’ve received JSON data. Further, we call converter.convert to parse the received response body data into an APIError object. Afterwards, we’ll return the created object.

retrofit2.Response.errorBody java code examples, retrofit.responseBodyConverter(Error.class, new Annotation[0]); Error error = errorConverter.convert(response.errorBody()); System.out.println("ERROR: " +� readTimeout(Duration duration) – The read timeout is applied to both the TCP socket and for individual read IO operations including on Source of the Response. writeTimeout(Duration duration) – The write timeout is applied for individual write IO operations.

Comments
  • Have you tried simply : Completable as the method return type?
  • @akarnokd no I have not. Should I?
  • If I use Completable, how to determine if the response was succesful or not?
  • Completable has two outcome: completes or fails. So doOnComplete instead of doOnSuccess.
  • Completable is likely not the right operator for an api request, we're probably interested in the response from the request, not just whether or not the request completed. Single is better choice here.
  • Thank you for your suggestion but i really need to work with Throwable since my logic very complex and dependant on Throwables.
  • so throw when the response is a failure. The RX chain will not throw for you on a failed http response.