FsToolkit.ErrorHandling

Searchâ€¦

README

`Result`

type in F#, and allows you to do clear, simple and powerful error handling.The library provides utility functions like

`map`

, `bind`

, `apply`

, `traverse`

, `sequence`

as well as computation expressions and infix operators to work with `Result<'a, 'b>`

, `Result<'a option, 'b>`

, `Async<Result<'a, 'b>>`

, `Async<Result<'a option, 'b>>`

, and `Result<'a, 'b list>`

.With adding a reference to

`FsToolkit.ErrorHandling.TaskResult`

you will also have access to computation expressions and infix operators related to `Task<Result<'a, 'b>>`

.It was inspired by Chessie and Cvdm.ErrorHandling (the latter has now been merged into FsToolkit.ErrorHandling).

FsToolkit.ErrorHandling targets .NET Standard 2.0 and .NET Framework 4.6.1 and supports Fable. â€‹

Nuget

Note

This documentation assumes some familiarity with standard functions like

`map`

, `apply`

, `bind`

, `traverse`

and `sequence`

and the problem these functions solve. If this is new to you, check out Scott Wlaschinâ€™s excellent tutorial on the subject.A motivating example

This example of composing a login flow shows one example of how this library can aid in clear, simple, and powerful error handling, using just a computation expression and a few helper functions. (The library has many more helper functions and computation expressions as well as infix operators; see the rest of the documentation for details.)

1

// Given the following functions:

2

// tryGetUser: string -> Async<User option>

3

// isPwdValid: string -> User -> bool

4

// authorize: User -> Async<Result<unit, AuthError>>

5

// createAuthToken: User -> Result<AuthToken, TokenError>

6

â€‹

7

type LoginError = InvalidUser | InvalidPwd | Unauthorized of AuthError | TokenErr of TokenError

8

â€‹

9

let login (username: string) (password: string) : Async<Result<AuthToken, LoginError>> =

10

asyncResult {

11

// requireSome unwraps a Some value or gives the specified error if None

12

let! user = username |> tryGetUser |> AsyncResult.requireSome InvalidUser

13

â€‹

14

// requireTrue gives the specified error if false

15

do! user |> isPwdValid password |> Result.requireTrue InvalidPwd

16

â€‹

17

// Error value is wrapped/transformed (Unauthorized has signature AuthError -> LoginError)

18

do! user |> authorize |> AsyncResult.mapError Unauthorized

19

â€‹

20

// Same as above, but synchronous, so we use the built-in mapError

21

return! user |> createAuthToken |> Result.mapError TokenErr

22

}

Copied!

Sponsor(s):

Last modified 6mo ago

Copy link