如何解析对 Throwable 的错误响应?

How to parse error response to Throwable?

我正在使用 RetrofitRxJava 发出这样的网络请求:

我如何声明请求:

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

我的通话方式:

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({
     }, {

     })

为了便于阅读,删除了一些代码。问题是,即使我收到 401 或 400 状态的回复,doOnSuccess 也被调用了。不应该在这里调用 doOnError 吗?我很迷惑。

因此我的 logact 显示 "Not Successful" 消息。当我收到 401 或 400 状态的响应时,如何确保调用 doOnErro

或者我可以解析对 Throwable 的传入响应并调用 doOnError() 函数吗?

真正的问题是,为什么要在请求失败时抛出异常?

此处遵循正确的流程,doOnSuccess 正在按预期调用,因为请求已返回响应而没有遇到抛出的异常。不管请求的响应是否成功。

你应该相应地处理你的响应状态,而不是抛出任意异常:

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);
     })

您得到的响应是正确的,响应显示在 doOnSuccess 中,因为您点击的 API 已成功命中,无论响应代码是什么。 当实际 API 调用失败时调用 doOnError,例如中间网络中断或某些服务器端问题。

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

您不能这样做,您可以将 doOnSuccess 中的响应处理为

 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?

正如你提到的你想要一个可抛出的东西,你可以使用 try-catch 块来实现它。

只需抛出一个自定义 EXCEPTION,您必须为其创建一个新的自定义异常 class。

将 Retrofit API 调用更改为 return Completable:

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

然后通过 doOnComplete 处理 "success case":

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