Skip to content

Errors

Option<A> is a value that may be absent: Some(value) or None. At runtime those are {:some, value} and :none. Some(None) is distinct from None and from nil.

Expected failure uses Result<Success, Error>: Ok(value) or Error(reason). with chains successful results. Each <- expression must produce a Result. The final expression is wrapped in Ok. The first error passes through unchanged.

mod errors
pub fn unwrap_or(option: Option<Integer>, fallback: Integer) -> Integer {
case option {
Some(value) -> value
None -> fallback
}
}
pub fn double(n: Integer) -> Result<Integer, :badarg> {
with {
value <- parse(n)
value * 2
}
}
fn parse(n: Integer) -> Result<Integer, :badarg> {
if n >= 0 {
Ok(n)
} else {
Error(:badarg)
}
}
pub fn double_or(n: Integer, fallback: Integer) -> Integer {
case double(n) {
Ok(value) -> value
Error(_) -> fallback
}
}

Elixir APIs that return A.t() | nil should be typed as A | nil, not as Option<A>. Use gale_std.option.from_nil and gale_std.option.to_nil explicitly at that boundary. A Result<A, Never> cannot contain Error, because Never is the empty type.

Raw bytes may not be valid UTF-8. string.from_binary returns Ok(text) when validation succeeds and Error(:invalid_utf8) otherwise:

pub fn from_bytes(bytes: Binary) -> Result<String, :invalid_utf8> {
gale_std.string.from_binary(bytes)
}