Today’s random F# code: Result instead of exceptions

Today’s random F# code from our app is about using Results instead of using exceptions.

Do you often need to get some data from the database, but it’s not sure that the requested data exists? And you don’t like using exceptions for this because exceptions are for really unusual things? Then use a Result:

Querying data with the help of Result

|!> is a custom operator for

asyncResult and Result.requireSome are from FsToolkit.ErrorHandling

We have an event-sourced system, so we first get the events from the database (getActiveRuns) and then project them into an ActivityStructure (ActivityStructure.projectSingle and Projection.current). And then we only continue if the structure was found. Otherwise, we return an Error (not throw an exception). The let! takes care of that.

The resulting value has the type Async<Result<AugmentedActiveRun list, ActivityTimeError>>.

Async = this is an asynchronous workflow
Result<Value, Error> = Either is succeeded, then we have a value; otherwise we have an error.
list = F# list

ActivityStructure.projectSingle projects the structure-events into a timeline. A timeline is a time series of values representing the structure and all changes ever made together with the information when it was changed.

Projection.current returns the current value from the timeline. If the structure was deleted, Option.None is returned.

AsyncResult.requireSome returns the value from an Option if it is `Some; otherwise the specified error is returned.


Async/TaskResult from FsToolKit is a pure joy to use. And the SequenceA/M functions under List

Almir Mesic

About the author

Urs Enzler

Add comment

By Urs Enzler

Recent Posts