Error handling
In the terminalela --spec error-handling
- The script stops on any failed command: it fails fast.
- A yes-or-no question to a command is a condition, with no
try:if cmdruns its block when the command exits 0, andif not cmdwhen it exits with any other code.else ifandwhiletake the same,while not test -f done. A condition's command that fails is an answer, not a failure, so the script goes on either way. tryis for a value: which failure it was (err = try grep -q x f, where grep's 1 is "not found" and 2 a broken file), the output of a command that may fail (out, err = try $(cmd)), why a call failed (data, err = try f()), or running a command and going on whatever happens (try rm old.log). Every form givesnullwhen nothing failed, and an Error (Errors as values) when something did. There is notryblock (catch, try and defer).trycovers a command that ran and exited with a code, a call that failed on its way, and afailat any depth below the call; nothing else. A mistake in the script, such as a command not found, a glob that matches nothing or an undefined variable, stops the script even undertry, so a typo is never hidden. An expression is no command:n = try $count + 1stops before line 1 and says to writen = $count + 1. Nor is a variable's key, position or field alone:try $m["k"]stops before line 1 and namesmap.get($m, "k", fallback)andhas($m, "k"), which ask for a key that may be missing.try $cmd, alone or with words after it, runs the programcmdholds, and so doestry $m["k"] args.- No hidden status variable like Bash's
$?. The interactive prompt asks how its last line went withlast_status(), which is an error in a script (SHELL.md, Startup config and prompt).
if git pull echo "ok"end if err = try grep -q TODO notes.mdif error.is($err, 2) echo "notes.md can't be read: $err.stderr" >&2end if
ela --lint points if try cmd == null to if cmd, and if try cmd != null to if not cmd.
try takes four forms, each giving what the failure was instead of stopping:
| Form | Gives |
|---|---|
err = try cmd | null when the command exits 0; otherwise an Error with its exit code and its stderr |
out, err = try $(cmd) | The output, trimmed as $( ) trims it, then null or the Error |
value, err = try call(...) | The call's values and null; or, when the call fails, its Error, with the values left unset |
err = try wait $job | null or the job's Error; for a list of jobs, a list of them in the list's order |
with time.each = "30s"; out, err = try $(git ls-remote $url)if $err != null echo "could not ask: $err" >&2end if data, err = try json.decode($body)n, err = try int($word)
try $( )andtryon a call are each the whole value of an assignment; anywhere else, as inif try $(cmd) == null, they are an error when the script is read.try $(cmd) | wc -landtry $(cmd) argsrun a command.- The number of names matches what the form gives, as every assignment does: one for a command, two for
$( ), the call's values and one more for a call._drops one. A call's count is known before it runs, from its proc'sreturns or the built-in's catalogue entry, and is checked then, whether the call fails or not; a call that returns nothing takes one name,err = try cleanup(). tryon a call catches what the call ran into on its way: afailin it or in any proc it calls, however deep, a failed command, a built-in or package proc refusing its input (json.decode,int,file.read, anhttpcall with no answer). A mistake in the script still stops it: an unknown name, a wrong argument, an undefined variable, a missing key or a position out of range, whichhasandlencheck first.err = try cmdandout, err = try $(cmd)take the command's stderr, where no redirect sends it elsewhere, into the Error rather than onto the terminal:$err.stderrholds all of it, and the message its last line.2>&1puts it in the output instead. A baretry cmd, which goes on whatever happens, leaves stderr on the terminal.- A value left unset by a failed call is an error to read, until it is assigned again.
- What
trygave is compared withnull, never with a number or text:if $err != ""orif $code != 0on a name onlytryassigns, andtry cmd == 0, stop before line 1 and name$err != nullanderror.is. An Error compared with a string or a number as the script runs is the same error.
Errors as values #
An Error is a value: what try gives when something failed, and what fail raises. It prints, in
echo, in a string and on stderr when nothing catches it, as its chain: its message, then each
cause's, joined with : .
proc read_config(path) if not file.exists($path) fail "reading $path: not found", Error.NOT_FOUND end if return file.read($path)end proc proc load_site() text, err = try read_config("config.toml") if $err != null fail "loading the site", $err end if return $textend proc site, err = try load_site()if error.is($err, Error.NOT_FOUND) echo "no config yet: $err"end if
no config yet: loading the site: reading config.toml: not found
| Field | Holds |
|---|---|
kind | One of the Error enum's kinds, below |
message | Its own message, without those of its causes |
cause | The Error it wraps, or null |
code | The exit code the script stops with when nothing catches it: a command's exit status, the number fail named, otherwise 1 |
stderr | What a command run by try wrote to stderr; "" for any other |
The kinds are the values of the built-in enum Error, written as Type's are: Error.NOT_FOUND.
| Kind | What failed |
|---|---|
NOT_FOUND | A file, folder, secret or program that isn't there: file.read of a missing file, a command that exits 127 |
PERMISSION | Something not allowed: permission denied, a read-only file system, a command that exits 126 |
INVALID | Input a built-in refuses: int("x"), a json.decode or toml.decode of broken text |
UNAVAILABLE | A service that isn't there or won't answer: no keyring on the session, a package not built yet |
TIMEOUT | A time limit: with time.block ran out, a command past with time.each, a command that exits 124 |
FAILED | Any other failure: a plain fail, a command's other exit codes, a full disk |
error.is($err)is true for any Error;error.is($err, Error.NOT_FOUND)when that kind is the Error's or any cause's;error.is($err, 2)when that exit code is. All three are false fornull, never an error (PACKAGES.md, Error values).$err != nullasks the same as the first.- A failed command's Error reads
grep -q x f: exited 2: grep: f: No such file or directory, the command as it ran, its exit code, then the last line of its stderr whentrytook it; its kind isNOT_FOUNDfor 127,PERMISSIONfor 126,TIMEOUTfor 124 andFAILEDfor any other code. - An Error's fields are read with a dot and never written: context is added by wrapping it,
fail "loading the site", $err.Error{...}is no literal:failmakes one. Erroras a parameter's type takes an Error:proc report(err: Error), anderr: Error?takesnulltoo.type_namecalls a kind anError kind.
fail #
fail "message" raises an Error with that message. The try on the nearest call above it catches
it, however many calls down it was raised; with none, the script stops: the lines deferred so far
run (defer), ela: and the Error's chain go to stderr, and the script exits 1.
fail takes the message first, then at most one more value, told apart by its type:
| Form | Raises |
|---|---|
fail "no config at $path" | An Error of kind Error.FAILED |
fail "no config at $path", Error.NOT_FOUND | An Error of that kind |
fail "loading the site", $err | An Error that wraps $err as its cause, and takes its kind |
fail "no input file given", 2 | An Error of kind Error.FAILED that, caught by nothing, exits 2; from 1 to 255 |
path = "/etc/app.toml"if not file.exists($path) fail "no config at $path", Error.NOT_FOUNDend ifif len($args) == 0 fail "no input file given", 2end if
ela: no config at /etc/app.toml
- An Error nothing catches exits 1 whatever its kind, unless
failnamed a number: the kind is for the script that catches it, and the exit code for the program that ran it. A wrap is its ownfail, sofail "loading the site", $errexits 1 whatever code$errheld;error.is($err, 2)still finds a cause's code. - A second extra value,
fail "x", Error.NOT_FOUND, 3, stops before line 1; so does a value of any other type,fail "x", "y", a literal number outside 1 to 255, or a literalnull. A cause that isnullas the script runs, from atrythat went well, is an error namingif $err != null. - In a
catch signalblock,failsets the exit code, asexitthere does, rather than 128 plus the signal. At the interactive prompt, an Error nothing catches is said asela:and its chain, and the prompt carries on. warnwrites a message and the script goes on;exitstops it with no message and no Error, which notrycatches. The message is text and the code a failure's:fail 42andfail "x", 0stop the script before line 1.- There is no
die. Written where it is no proc of the script's and no program onPATH, it stops the script before line 1:ela stops a script with fail "…". A script's ownproc dieis its own, and so is a programdie.erroris the package oferror.is; a commanderrorthat is no program is a command not found.