Stdlib typed errors

Every fallible stdlib module declares its own typed error enum. Silt’s Result(T, ModuleError) return shape lets user code pattern-match the failure modes directly instead of substring-matching on a String payload. Each enum is shown as its message ("{e}", println(e), the error: line of a main that returns it), so code that just wants a rendered error writes "{e}".

Variant naming

Every error enum is named after its module (io.IoError, tcp.TcpError), its variants carry no prefix (io.NotFound, tcp.Timeout), and where the platform can report more than the list (a file system, a socket, a server), its last variant is Other(String) for such a failure. An error enum and its variants are members of their module, reached through it, with or without the enum as a second qualifier:

import io

let a = io.NotFound("config.toml")

let b = io.IoError.NotFound("config.toml") -- same value

A selective import binds a variant by its bare name: import io.{ NotFound }. Two modules may have a variant of one name (tcp.Timeout and http.Timeout, io.Other and tcp.Other): a file imports at most one of them bare, and writes the others through their modules.

Enums

IoError (requires import io)

VariantFieldsMeaning
NotFound(String)pathfile or directory missing
FolderNotFound(String)folderthe folder a write goes into is missing
PermissionDenied(String)pathpermissions check failed
AlreadyExists(String)pathtarget already exists
InvalidInput(String)descriptionmalformed argument
Interrupted—syscall interrupted
UnexpectedEof—reader hit EOF mid-record
WriteZero—writer returned zero bytes
Other(String)platform messageunclassified platform error

JsonError (requires import json)

VariantFieldsMeaning
Syntax(String, Int, Int, Int)message, byte offset, line, columnsyntactically invalid JSON
TypeMismatch(String, String, Int, Int, Int)expected, actual (ending with the value’s path), byte offset, line, columnwrong JSON type for target
MissingField(String, Int, Int, Int)the field’s path, byte offset, line and column of its objectrequired field absent
Other(String, Int, Int, Int)message, byte offset, line, columnunclassified parse failure

TomlError (requires import toml)

VariantFieldsMeaning
Syntax(String, Int, Int, Int)message, byte offset, line, columnsyntactically invalid TOML
TypeMismatch(String, String, Int, Int, Int)expected, actual (ending with the value’s path), byte offset, line, columnwrong TOML type for target
MissingField(String, Int, Int, Int)the field’s path, byte offset, line and column of its tablerequired field absent
Other(String, Int, Int, Int)message, byte offset, line, columnunclassified parse failure
UnknownField(String, List(String), Int, Int, Int)the key’s path, the keys the table takes, byte offset, line and column of the keya key that no field of the record names

IntError (requires import int)

Returned by int.parse.

VariantFieldsMeaning
Empty—no digits: nothing but whitespace, or a sign alone
InvalidDigit(Int)byte offsetnon-digit character at offset
Overflow—value exceeds type max
Underflow—value below type min

FloatError (requires import float)

Returned by float.parse: the variants of IntError and NotFinite, in a type of its own (float.Empty is not int.Empty).

VariantFieldsMeaning
Empty—no digits: nothing but whitespace, or a sign or a point alone
InvalidDigit(Int)byte offsetcharacter that is no part of a number at offset
Overflow—literal above the Float range
Underflow—literal below the Float range
NotFinite—a spelled-out infinity or NaN ("inf", "NaN"): a Float is always finite

HttpError (requires import http)

VariantFieldsMeaning
Connect(String)messageno connection was made: refused, no route, no such host; a proxy that cannot be reached or refuses the tunnel, or a SOCKS proxy
Tls(String)messageTLS handshake / cert failure
Timeout—one of the request’s times passed
InvalidUrl(String)url, its user and password hiddenthe URL has a scheme other than http and https, is longer than 65,534 bytes, or has a user with a :; or a redirect leads to a location that is no URL or has such a scheme, or leads from https to http
InvalidResponse(String)messagewhat the server sent (or a proxy) is no HTTP, or its body is larger than 10,000,000 bytes
ClosedEarly—the server went away before the response was complete
TooManyRedirects—http.get or http.request was redirected more than ten times
Other(String)messageunclassified transport error

TcpError (requires import tcp)

VariantFieldsMeaning
Connect(String)messagetcp.connect made no connection (refused, unreachable, no such host)
Bind(String)messagetcp.listen bound no listener (address in use, not this machine’s, no address)
Tls(String)messageTLS handshake failure
Closed—connection closed, by this end or the other (also a reset, an abort, a broken pipe); for tcp.accept, the listener closed
Timeout—op exceeded its deadline
Other(String)messageunclassified socket failure

PostgresError (requires import postgres)

VariantFieldsMeaning
Connect(String)messagea connect that failed (refused port, unknown or unreachable host, missing database), URL parse, connect options, SQLSTATE class 08
Tls(String)messageTLS handshake / a server without TLS when sslmode requires TLS / cert read / connector build
AuthFailed(String)messageSQLSTATE class 28: a role or password the server refuses
Query(String, String)message, SQLSTATEserver-reported error
TypeMismatch(String, String, String)column, expected, actuala column whose type, or a cell whose value, does not fit the field it is decoded into
NoSuchColumn(String)columna field with no column in the result; SQLSTATE 42703
Closed—connection dropped, or a transaction used after it ended
Timeout—SQLSTATE 57014, a server that does not answer a connect, no free connection in the pool’s 30 s
TxnAborted—SQLSTATE 25P02 — rollback required
Other(String)messageunclassified pg error

TimeError (requires import time)

VariantFieldsMeaning
ParseFormat(String)messagethe text did not match a pattern that could have given the value
OutOfRange(String)messagefield out of valid range (e.g. month=13)
InvalidFormat(String)what is wrongthe pattern of time.format, time.format_date, time.parse or time.parse_date is no format, or one from which no text could give the value (no time of day for a DateTime, no date, empty)

BytesError (requires import bytes)

VariantFieldsMeaning
InvalidUtf8(Int)byte offsetdecode failed at offset
InvalidHex(String)messagebad hex string
InvalidBase64(String)messagebad base64 string
ByteOutOfRange(Int)valuelist element outside 0..=255

CryptoError (requires import crypto)

Returned by crypto.random_bytes.

VariantFieldsMeaning
InvalidLength(Int)the length asked fornegative, or above the 1 MiB cap
Other(String)messagethe OS CSPRNG failed

UuidError (requires import uuid)

Returned by uuid.parse.

VariantFieldsMeaning
Invalid(String)whynot a syntactically valid UUID

CsvError (requires import csv)

Returned by csv.split_line and csv.parse.

VariantFieldsMeaning
Syntax(String, Int)message, byte offsetthe text is no CSV: a quoted field that is not closed, text after a closing quote; a row with another number of fields than the header
TypeMismatch(String, String)expected, gota cell that is no value of its field’s type, with its line and column
MissingField(String)namethe header has no column for a field that is no Option
Other(String)messageunclassified failure

UrlError (requires import url)

Returned by url.parse, url.resolve, url.unescape and url.decode_form for a text that is no URL or no escaped text, and by the with_ functions that check their part. It does not repeat the text it was given, which may hold a password: it names the character that is wrong.

VariantFieldsMeaning
Invalid(String, Int)what is wrong, and the character where: counted from 0, as string.slice counts; the text’s length when it ends too earlythe text is no URL, or no escaped text
InvalidPart(String)what is wronga part a with_ function was given that the URL cannot hold

RegexError (requires import regex)

Returned by regex.compile for a pattern that does not compile.

VariantFieldsMeaning
InvalidPattern(String, Int)what is wrong, and the character of the pattern where: counted from 0, as string.slice countspattern did not parse
TooBig—compiled pattern exceeded size budget

Example: user-side pattern matching

import io

fn handle(e: io.IoError) -> String {
  match e {
    io.NotFound(path) -> "missing: {path}"
    io.FolderNotFound(folder) -> "no folder: {folder}"
    io.PermissionDenied(path) -> "denied: {path}"
    io.AlreadyExists(_) | io.InvalidInput(_) -> "recoverable"
    io.Interrupted | io.UnexpectedEof | io.WriteZero -> "transient"
    io.Other(msg) -> "unknown: {msg}"
  }
}

fn main() {
  println(handle(io.NotFound("config.toml")))
}
open in playground

Cross-module composition

Silt does not auto-convert between error types. A function that spans several stdlib modules wraps each module’s error in a local AppError enum and lifts each call’s Err into it with result.map_err. Variant constructors are first-class Fn(e) -> f values, so the second argument is just the constructor name — no closure wrapper needed:

import io
import json
import result

type Config {
  host: String,
  port: Int,
}

type AppError {
  IoProblem(io.IoError),
  JsonProblem(json.JsonError),
}

fn load_config(path: String) -> Result(Config, AppError) {
  let raw = io.read_file(path) |> result.map_err(IoProblem)?
  let cfg = json.parse(raw, Config) |> result.map_err(JsonProblem)?
  Ok(cfg)
}

A ? that ends a pipeline applies to the whole pipeline, so the pipeline is a single expression terminated by ?. See examples/cross_module_errors.silt for a longer walkthrough. A program can name each conversion once, in an impl of a From trait it declares, and pass it to result.map_err (result.map_err(r, AppError.from)): see Traits — Parameterized Traits.