outcome
An Error Handling library for Gleam. Inspired by https://github.com/lpil/snag and https://effect.website/.
Outcomes gives you:
- An error stack that makes it easier to track the path of an error.
- A way to distinguish between unexpected errors (Defect) and expected errors (Failure).
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.with_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.with_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.