outcome

Package Version Hex Docs

An Error Handling library for Gleam. Inspired by https://github.com/lpil/snag and https://effect.website/.

Outcomes gives you:

gleam add outcome
import outcome.{type Outcome}

fn using(email) {
  case signup(email) {
    Error(stack) -> io.print(outcome.pretty_print(stack))
    Ok(user) -> {
      //...
    }
  }
}

fn signup(email: String) -> Outcome(User, String) {
  use valid_email <- result.try(
    validate_email(email)
    |> outcome.context("In signup")
  )

  create_user(valid_email)
}

// An expected error should be marked as a failure
fn validate_email(email: String) -> Outcome(String, String) {
  Error("Invalid email")
    |> outcome.into_failure
}

// An unexpected error should be marked as a defect
fn create_user() -> Outcome(User, String) {
  Error("Some SQL error")
  |> outcome.into_defect
  |> outcome.context("In create_user")
}
using("invalid")

Failure: Invalid email

stack:
  Context: In signup
  Failure: Invalid email
using("sam@sample.com")

Defect: Some SQL error

stack:
  c: In signup
  c: In create_user
  d: Some SQL error

Further documentation can be found at https://hexdocs.pm/outcome.

Search Document