Home / Learn / 7 Results and failures
7.3 Handling a failure: the clauses
Page 4 of 12
7.3.1 What a handling clause is
A handling clause is a line under a call that says what to do if the call fails, or if its value is missing. Think of the instructions a store leaves for a clerk: "if the lamp is out of stock, offer the next model", "if the card is declined, ask for another". The instruction sits next to the task it belongs to, and nobody has to guess.
A clause stands on its own line, indented one level under the statement it handles. Una has five, in two families:
if error …handles an expression that fails:if error use,if error passandif error fail.if none …handles a value that is missing, anOptionthat isNone(section 7.1):if none useandif none fail.
The word after if error or if none is the decision: use a value and carry on, pass the failure on to your own caller, or fail with a variant of your own.
7.3.2 Why every call needs one
Una passes no failure on by itself. A call that can fail with no clause under it does not check. Leave out the clause under read_count:
--- a/src/shelves.una
+++ b/src/shelves.una
@@ -20,3 +20,2 @@
let units = read_count(raw)
- if error use 0
unitsuna check . reports:
[U3007] Error: `read_count` can fail with `CountError`; handle the failure with an `if error` clause, or wrap the call in `attempt`
╭─[ src/shelves.una:20:15 ]
│
20 │ let units = read_count(raw)
│ ───────┬───────
│ ╰───────── `read_count` can fail with `CountError`; handle the failure with an `if error` clause, or wrap the call in `attempt`
│
│ Note: run `una explain U3007` for an explanation
────╯The message names the call, read_count, and the kind it can fail with, CountError. The mark covers the call. The end of the message gives the two ways out: an if error clause under the call, or attempt, which keeps the outcome as a value (section 7.4). Una does not choose for you, because only you know whether a count that cannot be read should be 0, a failure of your own, or something to report.
7.3.3 How to write the clauses
| Clause | Use it when | After it |
|---|---|---|
if error use v |
You can carry on with a sensible value | The statement's value is v on failure; error can be used in v |
if error pass |
Your function fails with the same kind, and the caller should decide | The failure goes to your caller unchanged |
if error fail V(...) |
Your function fails with a different kind: translate it | Your function fails with V; inside V(...), error is the original failure |
if none use v |
The statement gives an Option, and None has a sensible default |
The value is unwrapped, or v |
if none fail V(...) |
None means the input is wrong |
The value is unwrapped, or your function fails with V |
"Unwrapped" means taken out of its Some: after the clause, the name holds a plain Int, not an Option[Int]. The step of this part has one function per clause, around a shelf count that a clerk types:
--- Why a shelf count could not be used.
kind CountError = NotCounted(shelf: Text) | Unreadable(raw: Text)
--- Why a shelf audit failed: the shelf, and the count's own failure as its cause.
kind AuditError = | BadShelf(shelf: Text, cause: CountError)
--- The units a clerk typed for a shelf. `if none fail`: a text that is not a number fails.
read_count(raw: Text) -> Int
fails CountError
=
let units = raw.trim.to_int()
if none fail Unreadable(raw)
units7.3.3.1 Fail on a missing value: if none fail
read_count turns a text into a count. to_int gives None for a text that is not a number, and if none fail Unreadable(raw) turns that None into a failure of read_count. After the clause, units is a plain Int: the clause has dealt with the other case.
7.3.3.2 Carry on with a value: if error use
--- `if error use`: carry on with 0 when the count cannot be read.
count_or_zero(raw: Text) -> Int
=
let units = read_count(raw)
if error use 0
unitsWhen read_count fails, units is 0, and the function goes on. count_or_zero cannot fail itself: the clause has handled every failure.
7.3.3.3 Pass it on: if error pass
--- `if error pass`: the same kind, `CountError`, so the failure goes to the caller as it is.
count_label(raw: Text) -> Text
fails CountError
=
let units = read_count(raw)
if error pass
"{units} units"count_label fails with CountError, the same kind as read_count, so if error pass hands the failure to count_label's caller as it is. Use it when the caller knows better what a failure means.
7.3.3.4 Use the failure in the value: error
--- `if error use`, with `error` in the value: a failure becomes a sentence.
shown(raw: Text) -> Text
=
let text = count_label(raw)
if error use explain(error)
textInside a clause, the name error holds the failure that happened, here a CountError. if error use explain(error) turns it into a sentence. explain is an ordinary function with a when over the variants, declared in the same module:
--- What a person reads about a count that could not be used.
explain(failure: CountError) -> Text
=
when failure
is NotCounted(shelf) -> "shelf {shelf} was not counted"
is Unreadable(raw) -> "'{raw}' is not a count"7.3.3.5 Translate it: if error fail
--- `if error fail`: a `CountError` becomes an `AuditError` that names the shelf.
audit(shelf: Text, raw: Text) -> Int
fails AuditError
=
read_count(raw)
if error fail BadShelf(shelf, cause: error)audit fails with AuditError, another kind, so it cannot pass a CountError on. if error fail BadShelf(shelf, cause: error) fails with its own variant instead, and keeps the original failure in the field cause, so nothing is lost. The clause here stands under the function's last line, the call whose value the function gives back: a clause may follow any statement that can fail, not only a let.
7.3.3.6 Carry on when a value is missing: if none use
--- `if none use`: a shelf with no count entered counts as 0.
counted(shelf: Text, entered: Option[Int]) -> Int
=
let units = entered
if none use 0
units
--- `if none fail`: a shelf with no count entered is a failure.
required(shelf: Text, entered: Option[Int]) -> Int
fails CountError
=
let units = entered
if none fail NotCounted(shelf)
unitsA clerk may not have entered a count yet, so entered is an Option[Int]. An if none clause may follow any expression of an Option type, here the parameter itself. counted treats a missing count as 0 units with if none use 0, and required treats it as a failure with if none fail NotCounted(shelf).
7.3.3.7 The clauses, run
main calls each function. To print what audit failed with, it uses attempt, which keeps a failure as a value that can be printed, Err(…); section 7.4 explains it.
let typed = count_or_zero(" 7 ")
let spelled = count_or_zero("seven")
let three = shown("3")
let cross = shown("x")
@console.print("{typed} {spelled} / {three} / {cross}")
let audited = attempt audit("A-12", raw: "seven")
@console.print("{audited}")
let missing = required("B-03", entered: None)
if error use -1
let found = counted("A-12", entered: Some(7))
let absent = counted("B-03", entered: None)
@console.print("{found} {absent} {missing}")7 0 / 3 units / 'x' is not a count
Err(BadShelf(shelf: "A-12", cause: Unreadable("seven")))
7 0 -1The second line shows translation at work: the AuditError names the shelf, and its cause keeps the CountError that started it.
7.3.4 Translating between layers with error
Most programs have layers: a low-level reader, a line reader above it, a report above that. Each layer has its own error kind, because each layer knows different things. The quantity reader knows the text was not a number, and the line reader also knows the line number. if error fail translates, and error keeps the original failure as a field, so nothing is lost. This step uses a smaller QuantityError than section 7.2, with one variant for both bounds, which is enough here:
module upload
kind QuantityError = NotANumber(raw: Text) | OutOfRange(value: Int)
--- Why a line of an uploaded file was rejected, with its line number.
kind LineError = MissingQuantity(line: Int) | BadQuantity(line: Int, cause: QuantityError)
parse_quantity(raw: Text) -> Int
fails QuantityError
=
let n = raw.trim.to_int()
if none fail NotANumber(raw)
if n < 1 or n > 99
fail OutOfRange(value: n)
else
n
--- The quantity on line `number` of an upload, `"SKU, quantity"`.
quantity_on_line(number: Int, text: Text) -> Int
fails LineError
=
let comma = text.find(text: ",")
if none fail MissingQuantity(line: number)
let raw = text.slice(start: comma + 1, end: text.len)
parse_quantity(raw)
if error fail BadQuantity(line: number, cause: error)
explain(failure: LineError) -> Text
=
when failure
is MissingQuantity(line) -> "line {line}: no quantity"
is BadQuantity(line, cause) -> "line {line}: {cause_text(cause)}"
cause_text(cause: QuantityError) -> Text
=
when cause
is NotANumber(raw) -> "'{raw.trim}' is not a number"
is OutOfRange(value) -> "{value} is not between 1 and 99"
show(number: Int, text: Text) -> Text
=
let outcome = attempt quantity_on_line(number, text: text)
when outcome
is Ok(value) -> "line {number}: {value} units"
is Err(failure) -> explain(failure)
--- Shows four lines of an upload.
pub main() -> Unit
uses @console: Console[print]
=
@console.print(show(1, text: "LAMP-01, 2"))
@console.print(show(2, text: "LAMP-01"))
@console.print(show(3, text: "LAMP-01, lots"))
@console.print(show(4, text: "LAMP-01, 500"))text.find(text: ",")andif none fail MissingQuantity(line: number).findgivesNonewhen the line has no comma. That is the input's fault, so it becomes a failure. After the clause,commais the comma's position.text.slice(start: comma + 1, end: text.len). The text after the comma.slicerequires its positions to lie inside the text (section 3.2), and the verifier proves it: whenfindgives a position, it also knows that the comma ends inside the text.if error fail BadQuantity(line: number, cause: error). This is translation.quantity_on_linefails withLineError, andparse_quantityfails withQuantityError, soif error passwould not be allowed (Passing a failure of another kind shows the diagnostic).erroris theQuantityErrorthat happened, and it is kept as thecause.explainandcause_text. Turning a failure into a message is an ordinarywhen. Becausewhenmust cover every variant, adding a variant toLineErrorlater makes the checker point at every message function that needs a new arm.attempt quantity_on_line(number, text: text)inshow.attemptkeeps the outcome as a value,Ok(value)orErr(failure), soshowcan print a message for either. Section 7.4 explains it.
una run . prints:
line 1: 2 units
line 2: no quantity
line 3: 'lots' is not a number
line 4: 500 is not between 1 and 997.3.5 How the clauses behave
7.3.5.1 Each clause on its own line, in order
A clause goes on its own line, indented one level under the statement. Written on the same line, it is U0101 (the clause on the same line). A statement takes each clause at most once, and when it has both families, if error comes first and if none second: the call's failure is decided before the value it gave. The other order is U0102 (if none before if error).
7.3.5.2 One call that can fail per statement
A call that can fail must be the whole expression of its statement or let, so that its clause handles exactly one call. Nesting it inside another call, as check_stock(parse_order(line)), is U3013 (nesting a call that can fail): give the inner call's result a name with let first, with its own clause.
7.3.5.3 What each clause requires
use v:vhas the type of the statement's value, since it takes the value's place. A value of another type, such as a text where anIntgoes, is U2001: the message names the type expected and the type found.pass: the call fails with the same kind as your function. Another kind is U3008 (passing a failure of another kind).fail V(...):Vis a variant of your function's kind, as for anyfail.erroris a name only inside anif errorclause, where it holds the failure.
7.3.5.4 A clause on a call that cannot fail
In editions 0.1 and 0.2, which this book uses, an if error clause under a call that cannot fail is accepted, and never runs. In edition 0.3, it is U3025, and una fix deletes it (chapter 19).
7.3.6 Choosing a clause
Which to use:
| The failure, or the missing value… | Use |
|---|---|
| Has a sensible value to carry on with | if error use v / if none use v |
| Is for your caller to decide, and your function fails with the same kind | if error pass |
| Needs your own terms, or your layer adds what it knows | if error fail V(cause: error) |
| Means the input is wrong | if none fail V |
| Must be kept to decide later, or counted | attempt (section 7.4) |
Prefer fail with your own variant over use with a value that only looks like an answer: a sentinel such as 0 is what section 7.2 set out to avoid. Use use when the value is honest, such as 0 units on a shelf nobody counted, or a price page that says "ask for a price".
7.3.7 Check yourself: handling clauses
shown passes through count_label, and count_or_zero carries on with 0. Predict the line:
let padded = shown(" 12 ")
let blank = count_or_zero("")
@console.print("{padded} / {blank}")Show the answer
12 units / 0read_count trims the text, so " 12 " reads as 12, count_label gives "12 units", and shown never needs its clause. The empty text is not a number, so read_count fails with Unreadable, and the clause in count_or_zero gives 0.