Home / Learn / 7 Results and failures

Release v0.4.0Edition 0.2

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:

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:

src/shelves.unadiff
--- a/src/shelves.una
+++ b/src/shelves.una
@@ -20,3 +20,2 @@
   let units = read_count(raw)
-    if error use 0
   units

una check . reports:

Diagnostic
[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:

steps/11-clauses/src/shelves.unauna
--- 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)
  units

7.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

steps/11-clauses/src/shelves.unauna
--- `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
  units

When 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

steps/11-clauses/src/shelves.unauna
--- `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

steps/11-clauses/src/shelves.unauna
--- `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)
  text

Inside 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:

steps/11-clauses/src/shelves.unauna
--- 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

steps/11-clauses/src/shelves.unauna
--- `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

steps/11-clauses/src/shelves.unauna
--- `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)
  units

A 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.

steps/11-clauses/src/shelves.unauna
  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}")
Output
7 0 / 3 units / 'x' is not a count
Err(BadShelf(shelf: "A-12", cause: Unreadable("seven")))
7 0 -1

The 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:

steps/13-translate/src/upload.unacheckrununa
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"))
  1. text.find(text: ",") and if none fail MissingQuantity(line: number). find gives None when the line has no comma. That is the input's fault, so it becomes a failure. After the clause, comma is the comma's position.
  2. text.slice(start: comma + 1, end: text.len). The text after the comma. slice requires its positions to lie inside the text (section 3.2), and the verifier proves it: when find gives a position, it also knows that the comma ends inside the text.
  3. if error fail BadQuantity(line: number, cause: error). This is translation. quantity_on_line fails with LineError, and parse_quantity fails with QuantityError, so if error pass would not be allowed (Passing a failure of another kind shows the diagnostic). error is the QuantityError that happened, and it is kept as the cause.
  4. explain and cause_text. Turning a failure into a message is an ordinary when. Because when must cover every variant, adding a variant to LineError later makes the checker point at every message function that needs a new arm.
  5. attempt quantity_on_line(number, text: text) in show. attempt keeps the outcome as a value, Ok(value) or Err(failure), so show can print a message for either. Section 7.4 explains it.

una run . prints:

Output
line 1: 2 units
line 2: no quantity
line 3: 'lots' is not a number
line 4: 500 is not between 1 and 99

7.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

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:

steps/11-clauses/src/shelves.unauna
  let padded = shown(" 12 ")
  let blank = count_or_zero("")
  @console.print("{padded} / {blank}")
Show the answer
Output
12 units / 0

read_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.

Next:7.4 Failures as values: attempt and Result