https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

Joffrey

05/18/2020, 7:31 AM
Hi guys, I often find it pretty useful to catch low-level exceptions and wrap them into more meaningful higher-level exceptions:
Copy code
try {
   // some suspending operations to connect to web socket
} catch(e: Exception) {
   throw WebSocketConnectionFailedException("meaningful high-level msg", e)
}
But when coroutine machinery like
withTimeout
is used around this code, it doesn’t behave as expected (we’re expecting a
TimeoutCancellationException
but get another one). To solve this problem, I add an extra catch to rethrow
CancellationException
as-is, but it doesn’t feel right…
Copy code
try {
   // so some operations to connect to web socket
} catch(e: CancellationException) {
   throw e // no wrapping here
} catch(e: Exception) {
   throw WebSocketConnectionFailedException("meaningful high-level msg", e)
}
Is there a better / built-in way to do this?
m

marstran

05/18/2020, 8:07 AM
The other way would be to catch a more specific exception than
Exception
, and pass everything else through.
☝🏼 1
3 Views