Skip to content

Provide catching alternative to AsyncResult.ofAsync? #361

@njlr

Description

@njlr

This code will throw an exception:

#r "nuget: FsToolkit.ErrorHandling, 5.2.0"

open FsToolkit.ErrorHandling

let workflow =
  async {
    failwith "kaboom"

    return 1
  }

asyncResult {
  let! x =
    workflow
    |> AsyncResult.ofAsync

  return x + 1
}
|> Async.RunSynchronously
|> printfn "%A"

But users might want to catch and print:

Error
  System.Exception: kaboom

The following behaves with catching behavior:

#r "nuget: FsToolkit.ErrorHandling, 5.2.0"

open FsToolkit.ErrorHandling

let workflow =
  async {
    failwith "kaboom"

    return 1
  }

asyncResult {
  let! x =
    workflow
    |> AsyncResult.ofAsync
    |> AsyncResult.catch id

  return x + 1
}
|> Async.RunSynchronously
|> printfn "%A"

Perhaps a catching helper should be provided?

[<RequireQualifiedAccess>]
module AsyncResult =

  let catchAsync (workflow : Async<'a>) : Async<Result<'a, exn>> =
    async {
      try
        let! res = workflow

        return Ok res
      with ex ->
        return Error ex
    }

This would be opposite of AsyncResult.getOrReraise.

Can send a PR. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions