The language / Failures
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
Kiln04
02 The language / 14
Failures
A method that can fail says so, and every call to it deals with that, where it happens.
Some things go wrong for reasons outside the program: a file that isn't there, text that isn't a number, a server that doesn't answer. Hematite keeps them in plain sight. A method that can fail says so in its return type, and every call to it decides, right where it's made, what happens when it does. You never have to guess which calls might fail, and no failure slips by unhandled.
- Say so
Int!is anInt, or a failure.- Fail
return failure("..."), with a message for people.- Handle it here
rescue error, and a block that gives a value instead.- Pass it on
try: if the call fails, so does the method.
Saying a method can fail
A method that can fail puts ! after its return type: Int! means "an Int, or a failure". Inside, it fails with return failure("..."), and the text says what went wrong. This one reads an age from text, and fails on text that isn't a whole number or is below zero:
export def parse_age(text: String): Int!
const age = try Int(text)
if age < 0
return failure("an age can't be negative: #{age}")
end
return age
endInt(text) can fail too, so the method passes its failure on with try (more on that below). A method that returns nothing but can fail is marked : !, like def save(name: String): !. Only a method's return type can have a !.
Every call deals with it
A call to a method that can fail is handled right where it's made. Its result can't be stored or passed on until a try or a rescue has dealt with the failure, so every such call is written one of two ways.
Handle it here: rescue
Write rescue error after the call, then a block. The block runs only when the call fails. It gets the failure's Error, whose message says what went wrong, and gives the value the call couldn't, with return:
import "ages"
const age = parse_age("forty") rescue error
print("not an age: #{error.message}") # prints not an age: "forty" isn't a whole number, so it can't become an Int
return 0
end
print(age) # prints 0
const other = parse_age("42") # error: parse_age("42") can fail; write 'try parse_age("42")' to pass the failure on, or 'parse_age("42") rescue ...' to handle itThe last line leaves its call unhandled, which is an error, and the message offers both ways to write it.
Pass it on: try
Often the method making the call isn't the place to decide what to do. Put try in front of the call: if it fails, so does the method, with the same failure. The method is then marked ! itself, and its own callers deal with the failure in turn:
import "ages"
def next_age(text: String): Int!
const age = try parse_age(text)
return age + 1
end
const age = next_age("41") rescue error
return 0
end
print(age) # prints 42try works in a method that can fail, and in the file's script (its top-level code). There, a failure stops the program with its message, and exit status 70.
Not this
Store the call's result first, and look at whether it worked later: const age = parse_age(text). That's an error, since a result can't be kept before its failure is dealt with.
Write this
Decide at the call: const age = try parse_age(text) to pass the failure on, or parse_age(text) rescue error and a block to give a value instead.
The ! is checked both ways
The mark has to be true in both directions, so a method's first line always tells you whether it can fail. A method that uses try or return failure(...) must be marked:
def show(text: String)
print(try Int(text)) # error: 'show' passes on a failure with 'try', so it can fail too; mark its return type with '!': ': !'
endAnd a method that's marked must be able to fail:
def one(): Int!
return 1
end
# error: 'one' is marked '!' but can't fail: it never returns a failure or passes one on with 'try'; remove the '!'The rescue block
A rescue block is never empty: it handles the failure, even if only by saying so. What else it does depends on where the call is.
Where the call's value is used, as in const age = parse_age(text) rescue error, the block gives a value in its place, with return on every path, the way map's block does. Its type is the call's. Where the value isn't used, like a call on a line of its own, the block runs, and can't return:
def check(count: Int): !
if count > 3
return failure("at most 3, not #{count}")
end
end
check(5) rescue error
print(error.message) # prints at most 3, not 5
endbreak and continue can't leave a rescue block. In a loop, give a value from the block, and decide after it whether to skip or stop.
Giving a failure a clearer message
return failure(...) fails the whole method, from anywhere in it, a rescue block included. That's how a method turns a failure from something it called into one that makes sense to whoever called it:
def port(text: String): Int!
const number = Int(text) rescue error
return failure("the port must be a number, not #{text}")
end
return number
end
port("http") rescue error
print(error.message) # prints the port must be a number, not http
endWhat went wrong: Error
Kinds of failure
Every Error has a kind, which code can check, and a message, which is for people. Check the kind when what to do depends on what went wrong, like treating a missing file as an empty one:
error.kind | When |
|---|---|
ErrorKind.missing | no such file or folder |
ErrorKind.denied | not allowed: by the system, or for whoever's asking |
ErrorKind.forbidden | refused as it stands, whoever sends it, like a form sent without its CSRF token |
ErrorKind.not_text | a file that isn't UTF-8 text |
ErrorKind.invalid | text in the wrong format, like Int("abc") |
ErrorKind.network | a server that can't be reached |
ErrorKind.timeout | a server that doesn't answer in time |
ErrorKind.conflict | what it would do clashes with what's there, like a second row with a value that must be unique |
ErrorKind.custom | a return failure(...) in the program's own code |
ErrorKind.other | anything else, like a full disk; the message says what |
A failure passed on with try keeps its kind. return failure(...) makes a custom one, unless it says which: return failure("there's no user 2", kind: ErrorKind.missing).
Compare kinds with ==, like if error.kind == ErrorKind.missing. More kinds will be added over time, and a when must list every value, so a when over kinds would break.
What else to know
tryandreturn failure(...)inside a block (each,map, ...) make the whole method fail.- A method that changes its object keeps the changes it made before it failed.
Erroris a type like any other, so a rescued error can be kept:var problems: [Error] = []. Only failures make one, though, and the name is Hematite's own, so no class of yours can take it:
const problem = new Error(message: "x") # error: an Error only comes from a failure: write 'return failure("...")' in a method marked '!', or use a class of your own