Home / Learn / 7 Results and failures

Release v0.4.0Edition 0.2

7.2 Declaring a failure: fails and fail

Page 3 of 12

7.2.1 What a failure is

A failure is a function's way of saying "I could not do this, and here is why", instead of giving back a value. Think of a card terminal at a till. Most of the time it says "approved". Sometimes it prints a slip that says "declined", or "card expired in March". The slip is not a price, and nobody mistakes it for one; it says what went wrong, with what the cashier needs to act on it.

In Una a failure is a value too, of a kind you declare. A few words name the parts, and the rest of this chapter uses them:

7.2.2 Why a function declares its failures

Take the quantity a customer types into an order form. It must be a whole number from 1 to 99. Without a way to fail, a function that reads it must still give back a number, so it gives 0 for anything it cannot use:

steps/05-sentinel/src/quantity.unacheckrununa
module quantity

--- The quantity typed into an order form: a whole number from 1 to 99. Any other text gives
--- 0, so the caller cannot tell a bad quantity from what went wrong with it.
quantity_or_zero(raw: Text) -> Int
=
  let n = raw.trim.to_int().or_else(default: 0)
  if n < 1 or n > 99 then 0 else n

--- One line of an order form: the typed text, the units, and the price of that many lamps.
priced(raw: Text) -> Text
=
  let units = quantity_or_zero(raw)
  "'{raw}': {units} units, {units * 1990} cents"

--- Prints four typed quantities, priced.
pub main() -> Unit
  uses @console: Console[print]
=
  @console.print(priced("3"))
  @console.print(priced("three"))
  @console.print(priced("0"))
  @console.print(priced("500"))

una run . prints:

Output
'3': 3 units, 5970 cents
'three': 0 units, 0 cents
'0': 0 units, 0 cents
'500': 0 units, 0 cents

The program runs, and three different problems come out the same way: a word, a zero, and a number too large all become "0 units, 0 cents". The caller cannot tell them apart, so it cannot tell the customer what to fix. Worse, 0 looks like a quantity, so code that forgets to check for it prices an empty order and carries on. A value used to mean "no value", such as this 0, is called a sentinel, and nothing in the type tells a caller to check for it.

A declared failure fixes both problems. The header says that the function can fail and with which kind, so a reader sees it without reading the body. Each way to fail is a variant of its own, with the data a message needs. And the checker refuses a call that does not say what to do when the function fails.

7.2.3 A function that fails: parse_quantity

Here is the quantity again, with a failure. The module declares the error kind, a function that fails with it, and a main that calls the function twice, once with good input and once with bad:

steps/06-quantity/src/quantity.unacheckrununa
module quantity

--- Why a quantity was rejected. Each variant carries what the user needs to fix it.
kind QuantityError = NotANumber(raw: Text) | TooSmall(value: Int) | TooLarge(value: Int)

--- The quantity typed into an order form: a whole number from 1 to 99.
parse_quantity(raw: Text) -> Int
  fails QuantityError
=
  let n = raw.trim.to_int()
    if none fail NotANumber(raw)
  if n < 1
    fail TooSmall(value: n)
  else if n > 99
    fail TooLarge(value: n)
  else
    n

--- Reads two typed quantities, one good and one bad.
pub main() -> Unit
  uses @console: Console[print]
=
  let typed = parse_quantity(" 3 ")
    if error use 0
  let spelled = parse_quantity("three")
    if error use 0
  @console.print("{typed} and {spelled}")
  1. kind QuantityError = …. An error kind is a sum kind like any other. Name the variants after what went wrong, not after where: NotANumber, not ReaderFailed.
  2. fails QuantityError. This header line says that parse_quantity can fail, and with which kind. A function declares at most one error kind.
  3. raw.trim.to_int() then if none fail NotANumber(raw). to_int returns an Option[Int] (section 7.1): None when the text is not a number. The clause on the next line turns None into a failure of this function. After it, n is a plain Int.
  4. fail TooSmall(value: n). This ends the function with that variant. fail can stand in any branch of an if, and the other branches give the value.
  5. if error use 0. In main, each call is followed by a handling clause, on its own line, indented under the call. Here it carries on with 0. Section 7.3 shows the others.

una run . prints:

Output
3 and 0

The first call returns 3. The second fails with NotANumber, and its clause carries on with 0. Here main chose 0 on purpose, at the call, where a reader sees it: the function itself no longer hides the failure.

7.2.4 How to write an error kind and fail

The step of this part is a card payment, with each form of an error kind and of fail:

steps/07-fail-forms/src/payment.unauna
--- How the payment service can fail. A kind with one variant starts with `|`.
kind ServiceError = | Timeout

--- Why a card payment was refused. Variants with data and without data can mix.
kind PaymentError = Declined | Expired(month: Int) | OverLimit(limit: Int, asked: Int)

--- The amount charged: `fail` in one branch of an `if`, the value in the other.
charge(cents: Int, limit: Int) -> Int
  fails PaymentError
=
  if cents > limit
    fail OverLimit(limit: limit, asked: cents)
  else
    cents

--- The month a card expires, if it is not before `today`: a variant with one field.
valid_until(month: Int, today: Int) -> Int
  fails PaymentError
=
  if month < today
    fail Expired(month)
  else
    month

--- A payment service that is always down: `fail` as the whole body.
always_down(cents: Int) -> Int
  fails ServiceError
=
  fail Timeout

--- A refusal with no detail: a variant without data.
refuse(cents: Int) -> Int
  fails PaymentError
=
  fail Declined

7.2.4.1 An error kind

An error kind is declared like any sum kind, with kind, a name, = and its variants separated by |:

7.2.4.2 fails in the header

fails PaymentError goes on its own line under the header line, indented two spaces, before =, next to any requires or uses line, in the order section 6.2 gives. A function names one error kind at most: every way it can fail is a variant of that kind.

7.2.4.3 fail in a branch

charge fails in the if branch and gives a value in the else branch:

steps/07-fail-forms/src/payment.unauna
--- The amount charged: `fail` in one branch of an `if`, the value in the other.
charge(cents: Int, limit: Int) -> Int
  fails PaymentError
=
  if cents > limit
    fail OverLimit(limit: limit, asked: cents)
  else
    cents

fail OverLimit(limit: limit, asked: cents) names the variant and gives each field by its label. When a variant has one field, its value may be given without the label, as fail Expired(month) in valid_until does. And a bare name that equals a field's name counts as that field's label, so BadShelf(shelf, cause: error) in section 7.3 is BadShelf(shelf: shelf, cause: error).

7.2.4.4 fail as the whole body

A function that always fails, such as a stand-in for a card terminal that is offline, has fail as its whole body, on its own line after =:

steps/07-fail-forms/src/payment.unauna
--- A payment service that is always down: `fail` as the whole body.
always_down(cents: Int) -> Int
  fails ServiceError
=
  fail Timeout

7.2.4.5 Failing on a missing value: if none fail

if none fail NotANumber(raw), in parse_quantity, is the short way to fail when a value is missing: it stands on the line under an expression that gives an Option. Section 7.3 covers it with the other clauses.

7.2.4.6 The forms, run

main calls each function once with a value that works and once with one that fails, and carries on with 0 after every failure:

steps/07-fail-forms/src/payment.unauna
pub main() -> Unit
  uses @console: Console[print]
=
  let paid = charge(4500, limit: 10000)
    if error use 0
  let refused = charge(24000, limit: 10000)
    if error use 0
  let until = valid_until(11, today: 10)
    if error use 0
  let expired = valid_until(3, today: 10)
    if error use 0
  let offline = always_down(4500)
    if error use 0
  let declined = refuse(4500)
    if error use 0
  @console.print("{paid} {refused} {until} {expired} {offline} {declined}")
Output
4500 0 11 0 0 0

charge gives 4500 under the limit and fails over it; valid_until gives 11 for a card that expires next month and fails for one that expired in March; the last two always fail.

7.2.5 How a failure behaves

7.2.5.1 fail ends the function

fail ends the function at once, as giving back a value does: no line after it runs, and the function gives no value. The caller's clause decides what happens next.

7.2.5.2 A function has one error kind

A function declares at most one kind in fails, and every fail in it must name a variant of that kind. To fail with a variant of another kind is U3009 (failing with a variant of another kind). When a function calls another that fails with a different kind, it translates the failure into its own, with if error fail (section 7.3).

7.2.5.3 Every call that can fail is handled

A call of a function that can fail must be followed by a clause that handles the failure, or be wrapped in attempt (section 7.4). Without one, the checker reports U3007 (forgetting the clause). Nothing passes a failure on unless a line says so.

7.2.5.4 Public functions declare; private ones may infer

A pub function must declare fails when it can fail: its header is what other modules rely on (section 6.3), and a fail in a pub function without fails is U3009 (a public function that fails without saying so). A private function may leave the line out, and the checker infers it, as it infers uses.

parse_quantity is private. Remove its fails line:

src/quantity.unadiff
--- a/src/quantity.una
+++ b/src/quantity.una
@@ -7,3 +7,2 @@
 parse_quantity(raw: Text) -> Int
-  fails QuantityError
 =

The program checks and prints the same thing, and una contract prints the header the checker inferred, marked with the comment -- inferred:

Terminal
$ una contract quantity.parse_quantity
--- The quantity typed into an order form: a whole number from 1 to 99.
parse_quantity(raw: Text) -> Int
  fails QuantityError -- inferred

So a private function without fails can still fail. Its header is the inferred one. Write the line anyway whenever the failure is part of what a caller should know: this book always does.

7.2.5.5 What is not a failure

Some problems never reach the program as failures, because they are ruled out before it runs. A division by zero, or a call that breaks a function's requires, is a proof obligation that the verifier must prove (section 5.4): a program with one it cannot prove does not run. A few problems outside the program's logic, such as running out of memory, stop the run instead; Reference lists them.

7.2.6 Failing as the function you are given: fails of

7.2.6.1 What fails of is

A parameter can hold a function, which the body then calls: its type, such as fn(Text) -> Int, says what the function takes and gives back, and a call passes a function by its name (section 10.2 teaches functions as values). Whether such a function can fail then depends on what it is given. Think of a cashier who rings up a cart with whatever price list the manager hands over: with the regular list, a SKU missing from it stops the sale; with a sale sign that prices everything at 5.00, nothing can go wrong. fails of price, a line of the header, says exactly that: this function fails when, and only when, its parameter price fails, and with the same kind.

7.2.6.2 Why a parameter's failures need a clause

The step of this part prices a cart of two SKUs with one of two price functions. listed knows two SKUs and fails with NoPrice for any other; flat prices everything at 500 and never fails:

steps/09-fails-of/src/pricing.unauna
--- Why a price list has no price for a SKU.
kind PriceError = | NoPrice(sku: Text)
steps/09-fails-of/src/pricing.unauna
--- The store's price list. It knows two SKUs, and fails for any other.
listed(sku: Text) -> Int
  fails PriceError
=
  if sku == "LAMP-01"
    1990
  else if sku == "DESK-02"
    15900
  else
    fail NoPrice(sku)

--- A flat price for every SKU, during a sale. It never fails.
flat(sku: Text) -> Int = 500

A parameter of the type fn(Text) -> Int holds a function that gives an Int and cannot fail. Here is a pub function that totals a cart with a price function, without fails of, called with the price list, which can fail:

src/pricing.unadiff
--- a/src/pricing.una
+++ b/src/pricing.una
@@ -8,3 +8,2 @@
 pub total_of_two(first: Text, second: Text, price: fn(Text) -> Int) -> Int
-  fails of price
 =

una check . reports, once for each call that passes listed:

Diagnostic
[U3009] Error: this function can fail with `PriceError`, which the expected function type does not allow
    ╭─[ src/pricing.una:34:65 ]
    │
 34 │   let known = total_of_two("LAMP-01", second: "DESK-02", price: listed)
    │                                                                 ───┬──
    │                                                                    ╰──── this function can fail with `PriceError`, which the expected function type does not allow
    │
    │ Note: run `una explain U3009` for an explanation

The mark points at the argument, listed. The message says that listed can fail with PriceError, and that the type of the parameter, fn(Text) -> Int, allows no failure. Writing fails PriceError on total_of_two would not help: the parameter's type would still allow no failure, and every call would need a clause, even with a price function that never fails.

7.2.6.3 How to write fails of

fails of p goes under the header, as fails does, and names a parameter p whose type is a function type written without fails. In the body, a call of p takes a clause, and if error pass hands its failure on:

steps/09-fails-of/src/pricing.unauna
--- The total of a cart of two SKUs, each priced by `price`. It fails when, and only when,
--- `price` fails, and with the same error kind.
pub total_of_two(first: Text, second: Text, price: fn(Text) -> Int) -> Int
  fails of price
=
  let first_cents = price(first)
    if error pass
  let second_cents = price(second)
    if error pass
  first_cents + second_cents

At each call of total_of_two, the failure is that of the argument. listed fails with PriceError, so a call with listed needs a clause; flat cannot fail, so a call with it needs none:

steps/09-fails-of/src/pricing.unauna
  let known = total_of_two("LAMP-01", second: "DESK-02", price: listed)
    if error use -1
  let flat_total = total_of_two("LAMP-01", second: "VASE-03", price: flat)
  @console.print("{known} {flat_total}")
Output
17890 1000

7.2.6.4 How fails of behaves

7.2.7 A sentinel, an Option or a failure

Which to use:

When the function cannot give a normal answer… Use
Never a sentinel value such as 0 or -1, which a caller can mistake for an answer
And "no answer" is a normal outcome, with nothing more to say an Option (section 7.1)
And the caller needs to know why, to act on it fails with an error kind

A price lookup for a SKU the store does not sell gives None: that is a normal answer. A quantity typed as "three" is a failure with a reason, NotANumber, which a form shows to the customer.

7.2.8 Check yourself: failures

Both calls fail. Predict the line:

steps/07-fail-forms/src/payment.unauna
  let over = charge(30000, limit: 10000)
    if error use -1
  let lapsed = valid_until(3, today: 10)
    if error use 99
  @console.print("{over} {lapsed}")
Show the answer
Output
-1 99

30000 is over the limit, so charge runs fail OverLimit(…): the function ends there and gives no value, and the clause under the call gives -1 instead. The card expired in month 3, before month 10, so valid_until fails with Expired, and its own clause gives 99. Each call's clause decides what a failure becomes at that call.

And one about fails of. VASE-03 is not in the price list:

steps/09-fails-of/src/pricing.unauna
  let unknown = total_of_two("LAMP-01", second: "VASE-03", price: listed)
    if error use -1
  @console.print("{unknown}")

What does it print?

Show the answer
Output
-1

total_of_two declares fails of price, so with listed it fails as listed does: listed fails with NoPrice for VASE-03, and if error pass hands that failure on. So the call fails, and the clause under it gives -1. The price of LAMP-01 alone is never returned.

Next:7.3 Handling a failure: the clauses