error
The one Error type behind throw, try and catch: a kind, a message, where it happened, and a retry policy.
import error
A function that can fail says so in its signature with throws, and reports the failure with throw. The caller either passes the error on with try, or handles it in a try: ... catch e: ... end block. What travels is always an Error from this package, so an error from a JSON decoder, a file read and your own code all look the same to the caller. Error and ErrorKind need no import; import error only for the helper functions below.
An Error has a kind, such as ErrorKind.NotFound, for the code to decide on, and a message for a person to read. Parsers also fill in where the problem is: an offset, a line and column, and a path such as $.users[3].age. A package can put a precise code of its own, such as json.trailing_data, next to the general kind. When an error passes through a layer that knows more, wrap adds that layer's explanation in front, and the kind stays the same.
Under the hood a throws function returns a Throws value, and try checks it right after the call. Nothing is unwound and nothing is hidden: defer runs as with any other early return, and a call that can throw always carries try or sits inside a try: block. A bug, such as an index out of bounds, is not an error value: it still stops the program, and catch does not see it.
Related: Option in the core package keeps a value or its absence in one place, for when a value may simply be missing rather than having gone wrong; declare your own Ok/Err enum when you want to store a result instead of handling it right away, as the enums lesson shows.
The things people get wrong:
- A call to a
throwsfunction needstryin front of it, or atry:block around it. The compiler refuses it otherwise (E155). tryon its own passes the error to the caller, so it only works in a function that is itselfthrows(E156). Inmain, either declarefunc main throws:or use atry:block.try x catch fallbackevaluates the fallback first, every time. Keep it a plain value.wrap,with_code,with_pathandwith_positionreturn a new error and leave the old one as it was.- Decide by
kindoris, not by reading the message: messages are for people and may change.
Errors through the layers of a program
A typical program has layers: one reads data, the next builds something from it, and the top one answers a user. Each layer that can fail is throws. A middle layer that has something to add catches the error, wraps it, and throws it again; the top layer decides what to do by kind.
func load user(id: int): str throws:
if id <= 0:
throw Error.New(ErrorKind.InvalidArgument, "the id must be positive")
end
if id != 7:
throw Error.New(ErrorKind.NotFound, "no such user").with_code("user." + id)
end
ret "Leila"
end
func greeting(id: int): str throws:
try:
ret "Welcome back, " + load user(id)
catch e:
throw e.wrap("could not build the greeting")
end
end
func status for(e: Error): int:
if e.is(ErrorKind.NotFound):
ret 404
else e.is(ErrorKind.InvalidArgument):
ret 400
end
ret 500
end
func main:
each id in [7, 3, -1]:
try:
println 200, greeting(id)
catch e:
println status for(e), e.ToStr()
if e.code != "":
println " code:", e.code
end
end
end
endWrapping keeps the kind of the original error, so the top layer can still see that the root cause was "not found" and answer 404. The code carries a detail, here the missing id, that the code can read without parsing text.
A retry loop
ShouldRetry answers the whole question in one call: is the error the kind that may go away by itself (Unavailable, Timeout or Io), and are there attempts left? DelayForAttempt gives the wait before the next try, doubling each time up to the maximum. When the attempts run out, the last error is wrapped and thrown to the caller.
import error
import sync
mut calls := 0
func fetch price(): int throws:
calls++
if calls < 3:
throw Error.New(ErrorKind.Unavailable, "the price service is busy")
end
ret 4200
end
func steady price(): int throws:
mut policy := error.NewRetryPolicy(5, 10, 80)
mut attempt := 1
until true:
try:
ret fetch price()
catch e:
if not error.ShouldRetry(policy, e, attempt):
throw e.wrap("gave up after " + attempt + " attempts")
end
wait := error.DelayForAttempt(policy, attempt)
println "attempt", attempt, "failed:", e.message, "| waiting", wait, "ms"
sync.SleepMs(wait)
end
attempt++
end
end
func main:
try:
println "price:", steady price()
catch e:
println e.ToStr()
end
bad := Error.New(ErrorKind.InvalidArgument, "unknown product")
mut policy := error.NewRetryPolicy(5, 10, 80)
println "retry a bad request?", error.ShouldRetry(policy, bad, 1)
endAn invalid argument is never retried: sending the same bad request again gives the same answer. In a server, keep the total wait well below the time the caller is willing to wait for you.
Collect every problem at once
For a form or a config file, stopping at the first mistake makes the user fix them one by one. An Error is an ordinary value, so collect them in a vector instead and show them all, with path naming the field each one is about. Throw once at the end if any were found.
struct Signup:
pub email: str = ""
pub age: int = 0
pub password: str = ""
end
func check(s: Signup): Vector<Error>:
mut problems := Vector {} as Vector<Error>
if not s.email.Includes("@"):
problems.Push(Error.New(ErrorKind.InvalidArgument, "the email has no @").with_path("email"))
end
if s.age < 13:
problems.Push(Error.New(ErrorKind.OutOfRange, "you must be at least 13").with_path("age"))
end
if s.password.Len() < 8:
problems.Push(Error.New(ErrorKind.InvalidArgument, "the password is too short").with_path("password"))
end
ret problems
end
func register(s: Signup): str throws:
problems := check(s)
if problems.Len() > 0:
throw Error.New(ErrorKind.InvalidArgument, problems.Len() + " fields need fixing")
end
ret "welcome, " + s.email
end
func main:
form := Signup { email = "sara.example.com", age = 11, password = "abc" }
problems := check(form)
println problems.Len(), "problems:"
each p in problems:
println " " + p.path + ":", p.message
end
try:
println register(form)
catch e:
println "not registered:", e.message
end
try:
println register(Signup { email = "sara@example.com", age = 30, password = "long enough" })
catch e:
println "not registered:", e.message
end
endChoosing a kind
| Kind | Use it when | Retry? |
|---|---|---|
Syntax | The input does not follow its format | No |
UnexpectedEnd | The input stopped in the middle of something | No |
TypeMismatch | A value has the wrong type, such as text where a number belongs | No |
MissingKey | A required key or field is absent | No |
OutOfRange | A number or index is outside what is allowed | No |
InvalidArgument | The caller passed bad input | No |
NotFound | The thing asked for does not exist | No |
PermissionDenied | The caller may not do this | No |
Unavailable | A service is down or busy | Yes |
Timeout | Something took too long | Yes |
Io | A file or device operation failed | Yes |
Internal | A broken invariant inside the program | No |
Keep messages short and in lower case without a final full stop, because to_str joins the context and the message with ": " into one sentence.
Types
RetryPolicy
struct RetryPolicy| Name | Type | Description |
|---|---|---|
max_attempts | int = 3 | The greatest number of attempts; three by default. |
base_delay_ms | int = 100 | The delay after the first failed attempt, in milliseconds; 100 by default. |
max_delay_ms | int = 5000 | The ceiling on the delay, in milliseconds; 5000 by default. |
import error
func main:
mut policy := error.NewRetryPolicy(4, 100, 1000)
println policy.max_attempts, policy.base_delay_ms, policy.max_delay_ms
e := Error.New(ErrorKind.Timeout, "the server did not answer")
println error.KindName(e.kind), error.IsRetryable(e)
mut attempt := 1
until error.ShouldRetry(policy, e, attempt):
println "attempt", attempt, "after", error.DelayForAttempt(policy, attempt), "milliseconds"
attempt++
end
println error.ShouldRetry(policy, Error.New(ErrorKind.InvalidArgument, "bad input"), 1)
endFunctions
KindName
func KindName(kind: ErrorKind): strto_str uses it when the message is empty.The example for this item is shown with the ones above: error-RetryPolicy.salam
IsRetryable
func IsRetryable(e: Error): boolThe example for this item is shown with the ones above: error-RetryPolicy.salam
NewRetryPolicy
func NewRetryPolicy(max_attempts: int, base_delay_ms: int, max_delay_ms: int): RetryPolicyThe example for this item is shown with the ones above: error-RetryPolicy.salam
DelayForAttempt
func DelayForAttempt(p &: RetryPolicy, attempt: int): intattempt failed: the base delay after the first, then doubling each time up to the ceiling. It does not sleep.The example for this item is shown with the ones above: error-RetryPolicy.salam
ShouldRetry
func ShouldRetry(p &: RetryPolicy, e: Error, attempt: int): boolattempt is still below max_attempts.The example for this item is shown with the ones above: error-RetryPolicy.salam