Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/FsToolkit.ErrorHandling/AsyncResult.fs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
namespace FsToolkit.ErrorHandling

open System.Threading.Tasks
#if !FABLE_COMPILER
open System.Runtime.ExceptionServices
#endif

[<RequireQualifiedAccess>]
module AsyncResult =
Expand Down Expand Up @@ -342,6 +345,20 @@ module AsyncResult =
| Choice2Of2 ex -> Error(exnMapper ex)
)

/// Gets the value in the Ok case or re-raises the exception in the Error case
let inline getOrReraise (input: Async<Result<'ok, exn>>) : Async<'ok> =
async {
match! input with
| Ok a -> return a
| Error exn ->
#if FABLE_COMPILER
return raise exn
#else
ExceptionDispatchInfo.Capture(exn).Throw()
return Unchecked.defaultof<_>
#endif
}

/// Lift Async to AsyncResult
let inline ofAsync (value: Async<'ok>) : Async<Result<'ok, 'error>> =
value
Expand Down
32 changes: 32 additions & 0 deletions tests/FsToolkit.ErrorHandling.Tests/AsyncResult.fs
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,37 @@ let catchTests =
<| Expect.hasAsyncErrorValue "unmapped" (AsyncResult.catch f (toAsync (Error "unmapped")))
]

let getOrReraiseTests =
let makeException () : exn =
try
failwith "Kaboom"
with exn ->
exn

testList "AsyncResult.getOrReraise tests" [
testCaseAsync "getOrReraise preserves message and stack-trace"
<| async {
let exn = makeException ()

let! captured =
async {
try
let! () =
AsyncResult.error exn
|> AsyncResult.getOrReraise

return failwith "Unexpected"
with exn ->
return exn
}

Expect.equal captured.Message exn.Message ""
#if !FABLE_COMPILER
Expect.equal captured.StackTrace exn.StackTrace ""
#endif
}
]

type CreatePostResult =
| PostSuccess of NotifyNewPostRequest
| NotAllowedToPost
Expand Down Expand Up @@ -1023,6 +1054,7 @@ let allTests =
teeErrorTests
teeErrorIfTests
catchTests
getOrReraiseTests
asyncResultCETests
asyncResultOperatorTests
zipTests
Expand Down
Loading