【问题标题】:Retrofit - delete was null but response body type was declared as non-null改造 - 删除为空,但响应主体类型被声明为非空
【发布时间】:2020-11-12 09:16:15
【问题描述】:

所以,在我删除 API 中的特定主题后,它会向我抛出此错误消息

deleteTopic 为空,但响应正文类型被声明为非空

主题已成功删除,但在我的客户端中,此响应以某种方式在我的 catch 块中解决

服务

@DELETE("topics/{id}")
    suspend fun deleteTopic(@Path("id") id:String)

回购

override suspend fun deleteTopic(id: String): Resource<Unit> {
        return Resource.Success(RetrofitClient.webservice.deleteTopic(id))
    }

视图模型

fun deleteTopic(id:String) = liveData(Dispatchers.IO) {
        emit(Resource.Loading())
        try {
            emit(repo.deleteTopic(id))
        }catch (e:Exception){
            emit(Resource.Failure(e))
        }
    }

由于某种原因,我成功删除了服务器中的主题,但是当它返回到我的客户端时,它会进入 catch 并返回我上面提到的这个异常,响应是 204 而不是内容,但是我该如何解决这个响应成功地告诉我这个操作已经正确完成了?

我很困惑,我在 github 上读到我必须返回 Response&lt;Unit&gt; 但我仍然很困惑为什么我应该这样做,它还说返回会阻止我的 4xx 返回码被抛出

【问题讨论】:

    标签: android kotlin mvvm retrofit android-architecture-components


    【解决方案1】:

    我认为问题在于您的删除端点确实返回空正文响应(仅 { })。如果可以,请将后端源更改为不这样做。否则,您可以添加一个自定义转换器来正确处理 4xx 状态代码。

    https://github.com/square/retrofit/issues/1554#issuecomment-178633697

    【讨论】:

    • 抱歉,我无法更改服务器,因为这是我需要执行的任务
    • 我已添加转换器,但问题仍然存在
    • 你试过在body.contentLength() == 0上设置断点,也许你的回复有内容?您是否也尝试过使用此github.com/square/retrofit/issues/1554#issuecomment-212941985 转换器?
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 2020-07-23
      • 2021-09-11
      • 2020-09-26
      • 2017-01-15
      相关资源
      最近更新 更多