Tin

Examples · learn/07-errors · 127 of 339

own-error

The error can be your own sum type, so callers can tell the failures apart.

examples/learn/07-errors/own-error.tintin run examples/learn/07-errors/own-error.tin
// The error can be your own sum type, so callers can tell the failures apart.
type WithdrawError = | Insufficient { short: int } | Negative

fn withdraw(balance: int, amount: int): Result<int, WithdrawError> {
  if amount < 0 { return Err(Negative) }
  if amount > balance { return Err(Insufficient { short: amount - balance }) }
  Ok(balance - amount)
}

fn explain(e: WithdrawError): string => match e {
  Insufficient { short } => "not enough: {short} short"
  Negative => "amount can't be negative"
}

fn main() {
  for amount in [30, 500, -5] {
    match withdraw(100, amount) {
      Ok(left) => print("ok, {left} left")
      Err(e) => print(explain(e))
    }
  }
}