exception

Types

pub type Exception {
  Errored(Dynamic)
  Thrown(Dynamic)
  Exited(Dynamic)
}

Constructors

  • Errored(Dynamic)

    An error was raised. On Erlang this would be caused by calling the erlang:error/1 function, or some other runtime error. On JavaScript this would be caused by throwing an Error object.

  • Thrown(Dynamic)

    A value was thrown. On Erlang this would be caused by calling the erlang:throw/1 function. On JavaScript this would be caused by throwing any non-Error value.

  • Exited(Dynamic)

    A process exited. On Erlang this would be caused by calling the erlang:exit/1 function. On JavaScript this variant is not used.

Functions

pub fn defer(cleanup: fn() -> a, body: fn() -> b) -> b

This function will run a cleanup function after the given body function, even if the body function crashes.

You should ideally never use this function! Exceptions are not flow control in Gleam, a result type should be used instead. This function is only if you need to perform some cleanup when a crash occurs.

Examples

pub fn run_with_lock(f: fn() -> a) -> a {
  let lock = acquire()
  use <- defer(fn() { release(lock) })
  f()
}
pub fn rescue(body: fn() -> a) -> Result(a, Exception)

This function will catch any crash and convert it into a result rather than crashing the process.

You should ideally never use this function! Exceptions are not flow control in Gleam, a result type should be used instead. This function is only if you need to perform some cleanup when a crash occurs, and then you should favour defer if possible.

Search Document