Standard library · System and tools

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 throw, 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 throw 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 throw function needs try in front of it, or a try: block around it. The compiler refuses it otherwise (E155).

•

try on its own passes the error to the caller, so it only works in a function that is itself declared throw (E156). In main, either declare func main throw: or use a try: block.

•

try x catch fallback evaluates the fallback first, every time. Keep it a plain value.

•

wrap, with_code, with_path and with_position return a new error and leave the old one as it was.

•

Decide by kind or is, 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 declared throw. 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.

error-guide-layers.salam
func load_user(id: int): str throw:
    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").WithCode("user." + id)
    end
    ret "Leila"
end

func greeting(id: int): str throw:
    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
end
Output
200 Welcome back, Leila
404 could not build the greeting: no such user
    code: user.3
400 could not build the greeting: the id must be positive

Wrapping 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.

error-guide-retry.salam
import error
import sync

mut calls := 0

func fetch_price(): int throw:
    calls++
    if calls < 3:
        throw Error.New(ErrorKind.Unavailable, "the price service is busy")
    end
    ret 4200
end

func steady_price(): int throw:
    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)
end
Output
attempt 1 failed: the price service is busy | waiting 10 ms
attempt 2 failed: the price service is busy | waiting 20 ms
price: 4200
retry a bad request? false

An 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.

error-guide-validate.salam
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 @").WithPath("email"))
    end
    if s.age < 13:
        problems.Push(Error.New(ErrorKind.OutOfRange, "you must be at least 13").WithPath("age"))
    end
    if s.password.Len() < 8:
        problems.Push(
            Error.New(ErrorKind.InvalidArgument, "the password is too short").WithPath("password")
        )
    end
    ret problems
end

func register(s: Signup): str throw:
    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
end
Output
3 problems:
  email: the email has no @
  age: you must be at least 13
  password: the password is too short
not registered: 3 fields need fixing
welcome, sara@example.com

Choosing a kind

KindUse it whenRetry?
SyntaxThe input does not follow its formatNo
UnexpectedEndThe input stopped in the middle of somethingNo
TypeMismatchA value has the wrong type, such as text where a number belongsNo
MissingKeyA required key or field is absentNo
OutOfRangeA number or index is outside what is allowedNo
InvalidArgumentThe caller passed bad inputNo
NotFoundThe thing asked for does not existNo
PermissionDeniedThe caller may not do thisNo
UnavailableA service is down or busyYes
TimeoutSomething took too longYes
IoA file or device operation failedYes
InternalA broken invariant inside the programNo

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

A retry policy.

NameTypeDescription
max_attemptsint = 3The greatest number of attempts; three by default.
base_delay_msint = 100The delay after the first failed attempt, in milliseconds; 100 by default.
max_delay_msint = 5000The ceiling on the delay, in milliseconds; 5000 by default.
error-RetryPolicy.salam
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)
end
Output
4 100 1000
timed out true
attempt 1 after 100 milliseconds
attempt 2 after 200 milliseconds
attempt 3 after 400 milliseconds
false

Functions

KindName

#
func KindName(kind: ErrorKind): str

A short English name for a kind, such as "not found"; to_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): bool

True when the error is transient and worth retrying: a timeout, an unavailable service or a read or write error.

The 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): RetryPolicy

Builds a policy with a maximum number of attempts and a base and maximum delay.

The example for this item is shown with the ones above: error-RetryPolicy.salam

DelayForAttempt

#
func DelayForAttempt(p &: RetryPolicy, attempt: int): int

How many milliseconds to wait after attempt number attempt 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): bool

True when the error is retryable and attempt is still below max_attempts.

The example for this item is shown with the ones above: error-RetryPolicy.salam