Skip to content

Instantly share code, notes, and snippets.

@gabrieljones
Last active January 18, 2024 15:00
Show Gist options
  • Save gabrieljones/51c3662e6c62b4d5f7115d03b216d3bb to your computer and use it in GitHub Desktop.
Save gabrieljones/51c3662e6c62b4d5f7115d03b216d3bb to your computer and use it in GitHub Desktop.
runCatching that does not catch Fatal throwables and does not catch CancellationException
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