Skip to content

Commit

Permalink
catchingUnwrapped
Browse files Browse the repository at this point in the history
  • Loading branch information
JesusMcCloud committed Oct 16, 2024
1 parent 8697729 commit 2ffd3bd
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions kmmresult/src/commonMain/kotlin/at/asitplus/NonFatal.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package at.asitplus

import kotlin.contracts.InvocationKind
import kotlin.contracts.contract

/**
* Throws any fatal exceptions. This is a re-implementation taken from Arrow's
* [`nonFatalOrThrow`](https://apidocs.arrow-kt.io/arrow-core/arrow.core/non-fatal-or-throw.html) –
Expand All @@ -19,3 +22,21 @@ expect inline fun Throwable.nonFatalOrThrow(): Throwable
* This helper hence provides the best of both worlds.
*/
inline fun <T> Result<T>.nonFatalOrThrow(): Result<T> = this.onFailure { it.nonFatalOrThrow() }


/**
* Non-fatal-only-catching version of stdlib's [runCatching], returning a [Result] --
* Re-throws any fatal exceptions, such as `OutOfMemoryError`. Relies on [Arrow](https://arrow-kt.io)'s
* [nonFatalOrThrow](https://apidocs.arrow-kt.io/arrow-core/arrow.core/non-fatal-or-throw.html) logic.
*/
@Suppress("TooGenericExceptionCaught")
inline fun <T> catchingUnwrapped(block: () -> T): Result<T> = runCatching (block).nonFatalOrThrow()

/**
* Non-fatal-only-catching version of stdlib's [runCatching] (calling the specified function [block] with `this` value
* as its receiver), directly returning a [Result] --
* Re-throws any fatal exceptions, such as `OutOfMemoryError`. Relies on [Arrow](https://arrow-kt.io)'s
* [nonFatalOrThrow](https://apidocs.arrow-kt.io/arrow-core/arrow.core/non-fatal-or-throw.html) logic.
*/
@Suppress("TooGenericExceptionCaught")
inline fun <T, R> T.catchingUnwrapped(block: T.() -> R): Result<R> = runCatching (block).nonFatalOrThrow()

0 comments on commit 2ffd3bd

Please sign in to comment.