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

Ehs*_*ari 5 error-handling android exception retrofit kotlin-coroutines

当使用 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."}
}
Run Code Online (Sandbox Code Playgroud)

Ehs*_*ari 16

你只需要这样做:

(exception as? HttpException)?.response()?.errorBody()?.string()
Run Code Online (Sandbox Code Playgroud)

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