tyc*_*czj 5 ktor kotlin-multiplatform
我正在将 Ktor 与 kotlin multiplatform 一起使用,我试图弄清楚为什么我没有收到任何抛出的异常。在我的客户端配置中,我使用HttpResonseValidator来检查返回的状态代码
private val client = HttpClient(clientEngine) {
install(JsonFeature) {
serializer = KotlinxSerializer(Json.nonstrict)
}
// addDefaultResponseValidation()
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)
}
}
handleResponseException { cause: Throwable ->
throw cause
}
}
}
Run Code Online (Sandbox Code Playgroud)
我401在我的服务器上返回 http 状态代码错误进行测试,所以我应该看到我的代码抛出 aClientRequestException并且validateResponse确实被调用,但我从未在控制台中看到任何异常,我的应用程序只是停止而没有任何指示发生任何事情。
这是我的电话
private suspend fun getDataForUrl(url:String, callback: (MyObject?) -> Unit){
val response = client.get<MyObject>(url)
callback(response)
}
Run Code Online (Sandbox Code Playgroud)
它被称为通过
fun getData(callback: (MyObject?) -> Unit){
launch(dispatcher()){
getDataForUrl("$BASE_URL", callback)
}
}
Run Code Online (Sandbox Code Playgroud)
当我用 try/catch 包围呼叫时
try{
val response = client.get<MyObject>(url)
catch(e:Exception){
}
Run Code Online (Sandbox Code Playgroud)
我确实得到了异常,但我真的不喜欢它在这里被捕获而不是在我的代码的上层。
当它周围没有 try/catch 时,为什么它会被吞没?
FATAL EXCEPTION我的 Kotlin 多平台项目中也有这个。
我的 Ktor 方法如下所示:
suspend fun requestToken(userName: String, password: String): AuthResponse {
return client.post {
url(urlOauth)
accept(ContentType.Application.Json)
body = FormDataContent(Parameters.build {
append("grant_type", "password")
append("username", userName)
append("password", password)
})
}
}
Run Code Online (Sandbox Code Playgroud)
HttpResponseValidator如果一切正常则使用。但是,当我强制执行错误时,例如,使用错误的 URL,则HttpResponseValidator不会使用该错误,并且我的应用程序(在本例中为 iOS 应用程序)崩溃。
当我打开生成的 Swift 类时,我看到此注释添加到我的方法中:
/**
@note This method converts instances of CancellationException to errors.
Other uncaught Kotlin exceptions are fatal.
*/
Run Code Online (Sandbox Code Playgroud)
这意味着所有其他错误都会使我的应用程序崩溃。与有所CancellationException关系suspend。
为了防止崩溃并出现错误,我添加了@Throws(CancellationException::class, ResponseException::class). 该方法现在如下所示:
/**
@note This method converts instances of CancellationException to errors.
Other uncaught Kotlin exceptions are fatal.
*/
Run Code Online (Sandbox Code Playgroud)
这就是我的使用方式:
@Throws(CancellationException::class, ResponseException::class)
suspend fun requestToken(userName: String, password: String): AuthResponse {
return client.post {
url(urlOauth)
accept(ContentType.Application.Json)
body = FormDataContent(Parameters.build {
append("grant_type", "password")
append("username", userName)
append("password", password)
})
}
}
Run Code Online (Sandbox Code Playgroud)
当我现在强制发生错误时,应用程序不会崩溃。相反,我收到错误并将其打印出来(在本例中)。
最后,我不知道为什么HttpResponseValidator在出现错误时不使用 ,但这会阻止FATAL EXCEPTION.
| 归档时间: |
|
| 查看次数: |
1318 次 |
| 最近记录: |