Skip to content

Commit 4fbcf32

Browse files
committed
Add try-with for compensation
1 parent c1ebc04 commit 4fbcf32

2 files changed

Lines changed: 10 additions & 4 deletions

File tree

src/FSharpPlus/Extensions/Task.fs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,9 @@ module Task =
327327

328328
[<ObsoleteAttribute("Swap parameters")>]
329329
let rec tryWith (body: unit -> Task<'T>) (compensation: exn -> Task<'T>) : Task<'T> =
330+
let runCompensation exn =
331+
try compensation exn
332+
with e -> Task.FromException<'T> e
330333
let unwrapException (agg: AggregateException) =
331334
if agg.InnerExceptions.Count = 1 then agg.InnerExceptions.[0]
332335
else agg :> Exception
@@ -336,11 +339,11 @@ module Task =
336339
if task.IsCompleted then
337340
match task with
338341
| Succeeded _ -> task
339-
| Faulted aex -> compensation (unwrapException aex)
342+
| Faulted aex -> runCompensation (unwrapException aex)
340343
| Canceled -> canceled
341344
else
342345
task.ContinueWith(fun (x: Task<'T>) -> tryWith (fun () -> x) compensation).Unwrap ()
343-
| Error exn -> compensation exn
346+
| Error exn -> runCompensation exn
344347

345348
[<ObsoleteAttribute("Swap parameters")>]
346349
let rec tryFinally (body: unit -> Task<'T>) (compensation : unit -> unit) : Task<'T> =

src/FSharpPlus/Extensions/ValueTask.fs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,9 @@ module ValueTask =
301301

302302
/// Used to de-sugar try .. with .. blocks in Computation Expressions.
303303
let inline tryWith ([<InlineIfLambda>]compensation: exn -> ValueTask<'T>) ([<InlineIfLambda>]body: unit -> ValueTask<'T>) : ValueTask<'T> =
304+
let runCompensation exn =
305+
try compensation exn
306+
with e -> ValueTask.FromException<'T> e
304307
let unwrapException (agg: AggregateException) =
305308
if agg.InnerExceptions.Count = 1 then agg.InnerExceptions.[0]
306309
else agg :> Exception
@@ -310,11 +313,11 @@ module ValueTask =
310313
if task.IsCompleted then
311314
match task with
312315
| Succeeded _ -> task
313-
| Faulted aex -> compensation (unwrapException aex)
316+
| Faulted aex -> runCompensation (unwrapException aex)
314317
| Canceled -> canceled
315318
else
316319
task.AsTask().ContinueWith(fun (x: Task<'T>) -> Task.tryWith (compensation >> fun x -> x.AsTask()) (fun () -> x)).Unwrap () |> ValueTask<'T>
317-
| Error exn -> compensation exn
320+
| Error exn -> runCompensation exn
318321

319322

320323
/// Used to de-sugar try .. finally .. blocks in Computation Expressions.

0 commit comments

Comments
 (0)