【问题标题】:Retrofit: How to deal with server side returning errors?改造:如何处理服务器端返回错误?
【发布时间】:2020-08-24 22:43:27
【问题描述】:

我在处理服务器端错误时遇到问题。

当我发送请求时,我希望得到一个如下所示的对象列表:

{"Search":[{"some data"}, {"more data"}]}

但是如果没有找到数据则返回:

{"Response":"False","Error":"Too many results."}

这会导致我的应用程序崩溃,因为它不是列表。我该如何解决?

改造界面

interface Api {

    @GET("https://www.website.com/")
    fun getInformation(@Query("apikey") apiKey: String, @Query("p") name: String): Call<List>
}

回购

 var list: MutableLiveData<List<Object>> = MutableLiveData()
 val call: Call<ObjectList> = ObjectApi.getObjectInformation(API_KEY, objectSearch)
        call.enqueue(object: Callback<ObjectList>{
            override fun onFailure(call: Call<ObjectList>, t: Throwable) {
                Log.d("TEST", "Error: ${t.message}")
            }

            override fun onResponse(call: Call<ObjectList>, response: Response<ObjectList>) {
                Log.d("TEST", "Success: ${response.body()}")
                val _list = response.body()
                list.value = _list.objects
            }

【问题讨论】:

    标签: android kotlin retrofit2


    【解决方案1】:

    您需要处理onResponse 中的错误响应以及成功调用。

    注意根据documents

    Note that transport-layer success (receiving a HTTP response code, headers and body) does not necessarily indicate application-layer success: response may still indicate an unhappy HTTP response code like 404 or 500.
    

    也就是说你需要处理onResponse里面的http状态码

    如果没有结果,你可以发送 404 并处理如下响应

    when(response.code) {
      200 -> // call response.body() and deserialize to object
      404 -> // you can use errorBody and thow exception or handle the error
      else -> // handle other error codes
    }
    
    
    

    errorBody

    【讨论】:

      【解决方案2】:

      我不知道您的 API 使用哪种语言,但有些语言只使用数组。我猜你的 Response 对象是ObjectList。能否也发送 Response 对象类的代码?

      【讨论】:

      • 是的,我正在用 Kotlin 写作。我的 ObjectList 只是一个模型类,它包含应该传入的数据。它只有字段。
      • 我所说的语言是指您要编写 API 本身的语言,而不是您的 Android 项目的语言。如果您可以发送 ObjectList 类的代码可以吗?
      猜你喜欢
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2014-02-10
      • 2011-07-24
      • 2017-12-13
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      相关资源
      最近更新 更多