Venkat
07/25/2023, 9:23 AMsuspend fun main() {
val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
val validServer = embeddedServer(CIO, port = 8080){}.start(false)
val addressReuseFailureServer = scope.async(start = CoroutineStart.LAZY) {
embeddedServer(
factory = CIO,
environment = applicationEngineEnvironment {
connector { port = 8080 }
},
configure = { reuseAddress = false }
).start(wait = false)
}
runCatching { addressReuseFailureServer.await() }.also { println(it) }
}
when I run the above code, the line runCatching {} doesn't;t catch the address reuse exception, instead, it propagates and crashes the application. Could anyone help me with this?Sam
07/25/2023, 9:26 AMasync always propagate to the outer scope in addition to being thrown from await(). In your example code, since you are using suspend fun main you do not need to create a separate CoroutineScope.Venkat
07/25/2023, 9:28 AMExceptions from async always propagate to the outer scope in addition to being thrown from await()But I'm catching that with runCathcing {}
Sam
07/25/2023, 9:29 AMawait(), but the exception will also be propagated to the parent scope. That’s just how async works.Venkat
07/25/2023, 9:31 AMVenkat
07/25/2023, 9:32 AMSam
07/25/2023, 9:32 AMsuspend fun main you do not need to create a separate CoroutineScope. If your actual application does need the additional scope, then yes, a supervisor scope could be a good solution 👍.Venkat
07/25/2023, 9:35 AMsuspend fun main() {
val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + SupervisorJob())
val validServer = embeddedServer(CIO, port = 8080){}.start(false)
val addressReuseFailureServer = scope.async(start = CoroutineStart.LAZY) {
embeddedServer(
factory = CIO,
environment = applicationEngineEnvironment {
connector { port = 8080 }
},
configure = { reuseAddress = false }
).start(wait = false)
}
runCatching { addressReuseFailureServer.await() }.also { println(it) }
}Venkat
07/25/2023, 9:35 AMVenkat
07/25/2023, 9:48 AMVenkat
07/25/2023, 12:32 PMfun main() {
val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
println("Caught an exception: ${throwable.message}")
}
val validServer = embeddedServer(CIO, port = 8080){}.start(false)
val addressReuseFailureServer =
embeddedServer(
factory = CIO,
environment = applicationEngineEnvironment { parentCoroutineContext = exceptionHandler;connector { port = 8080 } },
configure = { reuseAddress = false }
)
runCatching { addressReuseFailureServer.start(wait = false) }.also { println(it) }
}
I ended up with this,Venkat
07/25/2023, 12:33 PMFailure(kotlinx.coroutines.JobCancellationException: LazyStandaloneCoroutine is cancelling; job=LazyStandaloneCoroutine{Cancelling}@71423665)
Caught an exception: Address already in use
The above code catch all exception but don't whether it's the right way of doing it.Aleksei Tirman [JB]
07/30/2023, 8:32 AMCoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + SupervisorJob()).