Kotlin检测到服务器请求超时

时间:2022-10-14 21:39:37

Hi I'm still new to kotlin language, when requesting data to server for example in java:

嗨,我还是kotlin语言的新手,在向服务器请求数据时,例如在java中:

try{
    request_server();
}
catch(IOException e){
    //Some toast for network timeout for example
}

How can I check if that request if have network timeout in Kotlin?

如何在Kotlin中检查该请求是否有网络超时?

1 个解决方案

#1


2  

Kotlin does not have checked exceptions but that does not mean you cannot catch an IOException in Kotlin. There's no difference except the variable declaration in catch:

Kotlin没有检查异常,但这并不意味着你无法在Kotlin中捕获IOException。除了catch中的变量声明之外没有区别:

try{
    request_server();
}
catch(e: IOException){
    //Some toast for network timeout for example
}

It's very rare that you see such constructs in the language though. Since Kotlin has wonderful support for higher order functions, you can extract the error handling into such a function and make the business logic more obvious and also enable reuse.

尽管如此,你很少见到这种语言结构。由于Kotlin对高阶函数有很好的支持,因此您可以将错误处理提取到这样的函数中,使业务逻辑更加明显,并且还可以重用。

fun <R> timeoutHandled(block: () -> R): R {
    try {
        return block()
    } catch (e: IOException) {
        //Some toast for network timeout for example
    }
}

Used like this:

像这样使用:

val result = timeoutHandled {
    requestServer()
}

#1


2  

Kotlin does not have checked exceptions but that does not mean you cannot catch an IOException in Kotlin. There's no difference except the variable declaration in catch:

Kotlin没有检查异常,但这并不意味着你无法在Kotlin中捕获IOException。除了catch中的变量声明之外没有区别:

try{
    request_server();
}
catch(e: IOException){
    //Some toast for network timeout for example
}

It's very rare that you see such constructs in the language though. Since Kotlin has wonderful support for higher order functions, you can extract the error handling into such a function and make the business logic more obvious and also enable reuse.

尽管如此,你很少见到这种语言结构。由于Kotlin对高阶函数有很好的支持,因此您可以将错误处理提取到这样的函数中,使业务逻辑更加明显,并且还可以重用。

fun <R> timeoutHandled(block: () -> R): R {
    try {
        return block()
    } catch (e: IOException) {
        //Some toast for network timeout for example
    }
}

Used like this:

像这样使用:

val result = timeoutHandled {
    requestServer()
}