我最终做的是使用HttpResponseValidator
inHttpClientConfig
来捕获状态代码然后抛出异常
HttpResponseValidator{
validateResponse { response: HttpResponse ->
val statusCode = response.status.value
when (statusCode) {
in 300..399 -> throw RedirectResponseException(response)
in 400..499 -> throw ClientRequestException(response)
in 500..599 -> throw ServerResponseException(response)
}
if (statusCode >= 600) {
throw ResponseException(response)
}
}
}
通过这样做,我就能够通过我的自定义对象将错误传递回 UI
private suspend fun getCurrentWeatherForUrl(url:String, callback: (HttpResponseObject<MyObject>?) -> Unit){
var response:HttpResponseObject<MyObject>? = null
response = try{
client.get<HttpResponseObject<MyObject>>(url){
header("Authorization", "Bearer $authKey")
}
}catch (e:Exception){
HttpResponseObject(null, e.toString())
}
callback(response)
}
您还可以使用HttpResponse.receive()
获取序列化对象和响应数据
val response:HttpResponse = client.get(url)
val myObject:MyObject = response.receive<MyObject>()