When things go wrong#
Order lines arrive as text such as pen,2,150. Some will be wrong: a missing field, a quantity of zero, a price that is not a number. These are not bugs in your program; they are input. A function that can fail says so in its return type.
type Line {
name String
quantity, cents Int
}
fn parse_line(text String) Line! {
parts := text.split(",")
if parts.length() != 3 {
return error(Error(f"expected name,quantity,cents: {text}", kind: "EBADMSG"))
}
quantity := ok_or(
parts[1].parse_int(),
Error(f"quantity is not a number: {text}", kind: "EINVAL"),
)?
if quantity <= 0 {
return error(Error(f"quantity must be positive: {text}", kind: "EINVAL"))
}
cents := ok_or(
parts[2].parse_int(),
Error(f"price is not a number: {text}", kind: "EINVAL"),
)?
return ok(Line(parts[0].clone(), quantity, cents))
}
fn total(lines List[String]) Int! {
var sum = 0
for text in lines {
line := parse_line(text)?
sum += line.quantity * line.cents
}
return ok(sum)
}
fn main() Void {
good := total(["pen,2,150", "ink,1,899"])
print(f"good: {good.get_or(0)}")
bad := total(["pen,2,150", "ink,0,899"])
if bad.is_error() {
print(f"bad: {bad.err().message}")
}
broken := total(["pen,two,150"])
if broken.is_error() {
print(f"broken: {broken.err().message}")
}
}good: 1199
bad: quantity must be positive: ink,0,899
broken: quantity is not a number: pen,two,150Nothing is thrown. total returned an error value, and main decided what to print.
What to notice#
Int!means “anInt, or anError”. It is short forResult[Int, Error], andLine!works the same way. A caller cannot use the number without handling the other case.return ok(value)andreturn error(Error(...))are ordinary values with no hidden control flow.?unwraps a success. If the call failed, the function returns that error immediately. That is the whole error plumbing intotal: one?per call that can fail.parse_int()returns an optional, because the text might not be a number.ok_or(value, error)turns “nothing” into a specific error, so the message names the bad line.kindis a short code a caller can branch on, such as"EINVAL". The standard library uses the same codes, so you never import a per-module error type.good.get_or(0)reads a result with a fallback. For a full branch useif result.is_error() { ... }asmaindoes.
Try it#
Delete the ? after parse_line(text) and run the program. The compiler stops you: line is now a Result[Line, Error], which has no quantity. You cannot use a result as if it were its success value, and you cannot drop one unseen.
Absent is not an error#
T? is an optional: a value or nothing, with no error to explain. A map lookup and first() are optionals. Use T! when a failure needs a reason the caller can read, and T? when absence is normal.
Next: Who owns what . Exact rules: Results , Propagation with ? , Optionals .