Last active
January 18, 2024 15:00
-
-
Save gabrieljones/51c3662e6c62b4d5f7115d03b216d3bb to your computer and use it in GitHub Desktop.
runCatching that does not catch Fatal throwables and does not catch CancellationException
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inline fun <R> runCatchingNonFatal(block: () -> R): Result<R> { | |
return try { | |
Result.success(block()) | |
} | |
catch (t: Throwable) { | |
when (t) { | |
// VirtualMachineError includes OutOfMemoryError and other fatal errors | |
is VirtualMachineError, is ThreadDeath, is InterruptedException, is LinkageError, is CancellationException -> throw t | |
else -> Result.failure(t) | |
} | |
} | |
} | |
/* | |
See | |
- https://github.com/Kotlin/kotlinx.coroutines/issues/1814 | |
- https://github.com/scala/scala/blob/2.13.x/src/library/scala/util/control/NonFatal.scala | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment