Results

Gleam doesn't use exceptions, instead computations that can either succeed or fail return a value of the built-in Result(value, error) type. It has two variants:

  • Ok, which contains the return value of a successful computation.
  • Error, which contains the reason for a failed computation.

The type is generic with two type parameters, one for the success value and one for the error. With these the result can hold any type for success and failure.

Commonly a Gleam program or library will define a custom type with a variant for each possible problem that can arise, along with any error information that would be useful to the programmer.

This is advantageous over exceptions as you can immediately see what if any errors a function can return, and the compiler will ensure they are handled. No nasty surprises with unexpected exceptions!

A result value can be handled by pattern matching with a case expression, but given how frequently results are returned this can become unwieldy. Gleam code commonly uses the gleam/result standard library module and use expressions when working with results, both of which will be covered in later chapters.