Skip to content

Commit fc83c47

Browse files
authored
Adds getOrReraise and tests (#342)
1 parent 3491dbb commit fc83c47

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/FsToolkit.ErrorHandling/AsyncResult.fs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
namespace FsToolkit.ErrorHandling
22

33
open System.Threading.Tasks
4+
#if !FABLE_COMPILER
5+
open System.Runtime.ExceptionServices
6+
#endif
47

58
[<RequireQualifiedAccess>]
69
module AsyncResult =
@@ -342,6 +345,20 @@ module AsyncResult =
342345
| Choice2Of2 ex -> Error(exnMapper ex)
343346
)
344347

348+
/// Gets the value in the Ok case or re-raises the exception in the Error case
349+
let inline getOrReraise (input: Async<Result<'ok, exn>>) : Async<'ok> =
350+
async {
351+
match! input with
352+
| Ok a -> return a
353+
| Error exn ->
354+
#if FABLE_COMPILER
355+
return raise exn
356+
#else
357+
ExceptionDispatchInfo.Capture(exn).Throw()
358+
return Unchecked.defaultof<_>
359+
#endif
360+
}
361+
345362
/// Lift Async to AsyncResult
346363
let inline ofAsync (value: Async<'ok>) : Async<Result<'ok, 'error>> =
347364
value

tests/FsToolkit.ErrorHandling.Tests/AsyncResult.fs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,37 @@ let catchTests =
714714
<| Expect.hasAsyncErrorValue "unmapped" (AsyncResult.catch f (toAsync (Error "unmapped")))
715715
]
716716

717+
let getOrReraiseTests =
718+
let makeException () : exn =
719+
try
720+
failwith "Kaboom"
721+
with exn ->
722+
exn
723+
724+
testList "AsyncResult.getOrReraise tests" [
725+
testCaseAsync "getOrReraise preserves message and stack-trace"
726+
<| async {
727+
let exn = makeException ()
728+
729+
let! captured =
730+
async {
731+
try
732+
let! () =
733+
AsyncResult.error exn
734+
|> AsyncResult.getOrReraise
735+
736+
return failwith "Unexpected"
737+
with exn ->
738+
return exn
739+
}
740+
741+
Expect.equal captured.Message exn.Message ""
742+
#if !FABLE_COMPILER
743+
Expect.equal captured.StackTrace exn.StackTrace ""
744+
#endif
745+
}
746+
]
747+
717748
type CreatePostResult =
718749
| PostSuccess of NotifyNewPostRequest
719750
| NotAllowedToPost
@@ -1023,6 +1054,7 @@ let allTests =
10231054
teeErrorTests
10241055
teeErrorIfTests
10251056
catchTests
1057+
getOrReraiseTests
10261058
asyncResultCETests
10271059
asyncResultOperatorTests
10281060
zipTests

0 commit comments

Comments
 (0)