09 / 10
Errors
An error is a value you raise, match, add context to, or turn into data.
When a function cannot do its job, it raises an error with error. The work stops there, and the error travels up through the callers until one of them catches it.
(defn seats-left [seats crew] (if (> (count crew) seats) (error "too many people aboard" :seats seats :crew (count crew)) (- seats (count crew)))) (defn main [args] (print (seats-left 3 #["Alvin" "Hilvar"])) ;; catch gives the value of its first form, or of the clause that matches ;; the error. (print (catch (seats-left 1 #["Alvin" "Hilvar"]) e (str "caught: " (Error.message e)))) ;; The language's own errors are caught the same way. (print (catch (quot 1 0) e (str "caught: " (Error.message e)))))
Try it: Take the catch away from the second call, and leave (print (seats-left 1 #["Alvin" "Hilvar"])).
catch evaluates its first form. If that gives a value, catch gives it too. If it raises, the clauses after it are tried: a pattern, then what to give instead. A plain name, such as e, matches any error.
An error nobody catches
It ends the program, and the report has what was collected on the way: the message, the data passed with it, and each call it went through.
(defn seats-left [seats crew] (if (> (count crew) seats) (error "too many people aboard" :seats seats :crew (count crew)) (- seats (count crew)))) (defn check [ship] (seats-left ship.seats ship.crew)) (defn main [args] (print "boarding") (print (check #{:seats 1 :crew #["Alvin" "Hilvar"]})) (print "away"))
Try it: Give the ship two seats. The program reaches away.
The keywords and values after the message, :seats seats, are data that travels with the error. A handler can read them, and the report prints them.
Errors with a shape
A message is enough for a quick error. A library's errors deserve more: an enum that lists them, with a field for whatever a caller needs to know. catch then tells them apart by pattern, the way match does.
;; An error can be any value. An enum says which errors there are. (defenum ConfigError (NotFound [path]) (Invalid [path line reason])) (defn read-config [path] (match path "app.conf" #{:port 8080} "old.conf" (error (ConfigError.Invalid path: path line: 3 reason: "no port")) _ (error (ConfigError.NotFound path: path)))) ;; catch takes patterns, as match does. (defn port [path] (catch (get (read-config path) :port) (ConfigError.NotFound path:) f"no file {path}" (ConfigError.Invalid line: reason:) f"line {line}: {reason}")) (defn main [args] (print (port "app.conf")) (print (port "old.conf")) (print (port "lost.conf")))
Try it: Remove the ConfigError.Invalid clause from port. The error for old.conf is no longer caught there, so it goes on up and ends the program.
An error is whatever value you raise. It needs no base class and no declaration of which function may raise it.
Saying what you were doing
The function that fails knows what went wrong. It does not know why it was called. context lets a caller add that: every error that passes through it gains a line, and a hint if you give one.
(defn parse-port [text] (if (= text "8080") 8080 (error f"not a port: {text}"))) (defn load-config [path] ;; context adds a line to the report of any error that passes through. (context f"loading {path}" hint: "the port is a number from 1 to 65535" (parse-port "eighty"))) (defn main [args] (print (load-config "app.conf")))
Try it: Wrap the call in main in a second context, with "starting the server". The report gets a second while: line.
The error itself is not replaced or wrapped. A catch further up still sees the same value, and the report still points at the line that raised it.
From an error to a value
Sometimes a failure is an ordinary result: you try ten files and want to know which ones failed. attempt turns the outcome of a form into a value, (Ok value: …) or (Err failure: …), to keep or to match on. must turns it back.
(defn parse-port [text] (if (= text "8080") 8080 (error f"not a port: {text}"))) (defn main [args] ;; attempt turns an error into a value: Ok or Err. (print (attempt (parse-port "8080"))) (for [text #["8080" "eighty"]] (match (attempt (parse-port text)) (Ok value:) (print "the port is" value) (Err failure:) (print "failed:" (Error.message failure.error)))) ;; must turns it back: the value of an Ok, or the error of an Err. (print (must (attempt (parse-port "8080")))))
Try it: Call must on the attempt that failed: (must (attempt (parse-port "eighty"))). The error is raised again, as if it had never been caught.
Cleaning up
defer names something to do when the function ends, however it ends: with a value, or with an error on its way up.
;; defer runs when the function ends, whichever way it ends. (defn visit [place fail?] (print " opening" place) (defer (print " closing" place)) (if fail? (error f"{place} is sealed") f"saw {place}")) (defn main [args] (print (visit "the tomb of Yarlan Zey" false)) (print (catch (visit "the Tower of Loranne" true) e (str "caught: " (Error.message e)))))
Try it: Add a second defer after the first. They run in reverse: the last one named is the first to run.
Under all of this is one mechanism, and errors are only its most familiar use: effects.