改进:如何处理服务器端返回错误?

时间:2020-08-24 22:43:27

标签: android kotlin retrofit2

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

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

{"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
            }

2 个答案:

答案 0 :(得分:2)

您需要通过成功调用来处理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

答案 1 :(得分:0)

我不知道您的API使用哪种语言,但是某些语言仅使用数组。我猜您的响应对象是ObjectList。您还可以发送Response对象类的代码吗?