gpt4 book ai didi

android - 使用Retrofit + Coroutine时如何获取服务器返回的错误体

转载 作者:行者123 更新时间:2023-12-05 00:10:57 31 4
gpt4 key购买 nike

当使用 Coroutine 和 Retrofit 来调用网络 api 时,如果服务器返回错误(响应代码!= 200),我们将得到一个异常。我的问题是如何查找/读取服务器通过异常发送的错误主体(Json 格式)?

try{
apiService.login()
}catch(exception:Exception){
//How to read error body from exception
//Error body example: {"ok":false,"error":"Incorrect username or password."}
}

最佳答案

你只需要这样做:

(exception as? HttpException)?.response()?.errorBody()?.string()

这将以 Json 格式返回错误正文。

关于android - 使用Retrofit + Coroutine时如何获取服务器返回的错误体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67378400/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com