【问题标题】:How to parse error response to Throwable?如何解析对 Throwable 的错误响应?
【发布时间】:2020-05-22 09:39:00
【问题描述】:

我正在使用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 显示“不成功”消息。当我收到 401 或 400 状态的响应时,如何确保调用 doOnErro

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

【问题讨论】:

  • 您是否尝试过简单地将: Completable 作为方法返回类型?
  • @akarnokd 不,我没有。我应该吗?
  • 如果我使用Completable,如何判断响应是否成功?
  • Completable 有两个结果:完成或失败。所以doOnComplete 而不是doOnSuccess
  • Completable 可能不是 api 请求的正确运算符,我们可能对请求的响应感兴趣,而不仅仅是请求是否完成。单身是更好的选择。

标签: android parsing retrofit response rx-java2


【解决方案1】:

将 Retrofit API 调用更改为返回 Completable

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

然后通过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({  }, {  })

【讨论】:

    【解决方案2】:

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

    这里正在遵循正确的流程,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);
         })
    

    【讨论】:

    • 感谢您的建议,但我真的需要与Throwable 合作,因为我的逻辑非常复杂并且依赖于Throwables。
    • 所以当响应失败时抛出。 RX 链不会在 HTTP 响应失败时为您抛出。
    【解决方案3】:

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

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

    您不能这样做,您可以将 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();
     }
    

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

    正如你提到的你想要一个 throwable,你可以通过使用 try-catch 块来实现它。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      • 2023-03-20
      • 2019-02-05
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多