Skip to main content

Error values

All expressions with the exception of collections can evaluate as an error value. For instance when reading a dataset as a string, from a wrong URL:

let x = String.Read(Http.Get("http://broken/location"))

Because the URL http://broken/location can't be downloaded, String.Read evaluates as an error:

"service error: http error: host not found for http://broken/location"

An error is a value. It doesn't interrupt the execution when it occurs. In the example below, x is declared as a list of two items, two strings read from two URLs using String.Read. The first call to String.Read fails because the host doesn't resolve, and evaluates as an error. The second call succeeds. Both values end up in the list.

let x = [
String.Read(Http.Get("http://broken/location")), // that one fails
String.Read(Http.Get("http://www.example.com")) // that one succeeds
]

Here's the value of x:

[
"http error: host not found for http://broken/location",
"... <the HTML page downloaded from www.example.com> ..."
]

Error propagation

If an error value is passed as a parameter to a function, the error propagates. In the program below, List.Transform is used to apply String.Length to both items of x. When it is applied to the error value, String.Length cannot compute the string length and evaluates as an error:

let x = [
String.Read(Http.Get("http://broken/location")),
String.Read(Http.Get("http://www.example.com"))
]
in List.Transform(x, s -> String.Length(s))

The code executes till the end and returns a list of items, one of which is an error.

[
"http error: host not found for http://broken/location",
1256
]

Error handling

To check if a value is an error, use Try.IsError.

let
x: string = String.Read(Http.Get("http://broken/location"))
in
Try.IsError(x) // true

Try.IsSuccess is also available.

let
x: string = String.Read(Http.Get("http://broken/location"))
in
Try.IsSuccess(x) // false

Building and returning custom errors

Building a custom error value is also possible with Error.Build(<message>). This is useful if willing to return an error from a function. Here is an example function that divides by two its argument n, but returns an error when the number isn't even:

let
half(n: int) =
if n % 2 == 0 then
n / 2
else
Error.Build(String.From(n) + " isn\'t even")
in
List.Transform([1, 2, 3, 4], (i) -> half(i))

evaluates to:

[
"1 isn't even",
1,
"3 isn't even",
2
]