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)
| Variant | Fields | Meaning |
|---|
NotFound(String) | path | file or directory missing |
FolderNotFound(String) | folder | the folder a write goes into is missing |
PermissionDenied(String) | path | permissions check failed |
AlreadyExists(String) | path | target already exists |
InvalidInput(String) | description | malformed argument |
Interrupted | — | syscall interrupted |
UnexpectedEof | — | reader hit EOF mid-record |
WriteZero | — | writer returned zero bytes |
Other(String) | platform message | unclassified platform error |
JsonError (requires import json)
| Variant | Fields | Meaning |
|---|
Syntax(String, Int, Int, Int) | message, byte offset, line, column | syntactically invalid JSON |
TypeMismatch(String, String, Int, Int, Int) | expected, actual (ending with the value’s path), byte offset, line, column | wrong JSON type for target |
MissingField(String, Int, Int, Int) | the field’s path, byte offset, line and column of its object | required field absent |
Other(String, Int, Int, Int) | message, byte offset, line, column | unclassified parse failure |
TomlError (requires import toml)
| Variant | Fields | Meaning |
|---|
Syntax(String, Int, Int, Int) | message, byte offset, line, column | syntactically invalid TOML |
TypeMismatch(String, String, Int, Int, Int) | expected, actual (ending with the value’s path), byte offset, line, column | wrong TOML type for target |
MissingField(String, Int, Int, Int) | the field’s path, byte offset, line and column of its table | required field absent |
Other(String, Int, Int, Int) | message, byte offset, line, column | unclassified 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 key | a key that no field of the record names |
IntError (requires import int)
Returned by int.parse.
| Variant | Fields | Meaning |
|---|
Empty | — | no digits: nothing but whitespace, or a sign alone |
InvalidDigit(Int) | byte offset | non-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).
| Variant | Fields | Meaning |
|---|
Empty | — | no digits: nothing but whitespace, or a sign or a point alone |
InvalidDigit(Int) | byte offset | character 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)
| Variant | Fields | Meaning |
|---|
Connect(String) | message | no 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) | message | TLS handshake / cert failure |
Timeout | — | one of the request’s times passed |
InvalidUrl(String) | url, its user and password hidden | the 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) | message | what 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) | message | unclassified transport error |
TcpError (requires import tcp)
| Variant | Fields | Meaning |
|---|
Connect(String) | message | tcp.connect made no connection (refused, unreachable, no such host) |
Bind(String) | message | tcp.listen bound no listener (address in use, not this machine’s, no address) |
Tls(String) | message | TLS 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) | message | unclassified socket failure |
PostgresError (requires import postgres)
| Variant | Fields | Meaning |
|---|
Connect(String) | message | a connect that failed (refused port, unknown or unreachable host, missing database), URL parse, connect options, SQLSTATE class 08 |
Tls(String) | message | TLS handshake / a server without TLS when sslmode requires TLS / cert read / connector build |
AuthFailed(String) | message | SQLSTATE class 28: a role or password the server refuses |
Query(String, String) | message, SQLSTATE | server-reported error |
TypeMismatch(String, String, String) | column, expected, actual | a column whose type, or a cell whose value, does not fit the field it is decoded into |
NoSuchColumn(String) | column | a 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) | message | unclassified pg error |
TimeError (requires import time)
| Variant | Fields | Meaning |
|---|
ParseFormat(String) | message | the text did not match a pattern that could have given the value |
OutOfRange(String) | message | field out of valid range (e.g. month=13) |
InvalidFormat(String) | what is wrong | the 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)
| Variant | Fields | Meaning |
|---|
InvalidUtf8(Int) | byte offset | decode failed at offset |
InvalidHex(String) | message | bad hex string |
InvalidBase64(String) | message | bad base64 string |
ByteOutOfRange(Int) | value | list element outside 0..=255 |
CryptoError (requires import crypto)
Returned by crypto.random_bytes.
| Variant | Fields | Meaning |
|---|
InvalidLength(Int) | the length asked for | negative, or above the 1 MiB cap |
Other(String) | message | the OS CSPRNG failed |
UuidError (requires import uuid)
Returned by uuid.parse.
| Variant | Fields | Meaning |
|---|
Invalid(String) | why | not a syntactically valid UUID |
CsvError (requires import csv)
Returned by csv.split_line and csv.parse.
| Variant | Fields | Meaning |
|---|
Syntax(String, Int) | message, byte offset | the 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, got | a cell that is no value of its field’s type, with its line and column |
MissingField(String) | name | the header has no column for a field that is no Option |
Other(String) | message | unclassified 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.
| Variant | Fields | Meaning |
|---|
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 early | the text is no URL, or no escaped text |
InvalidPart(String) | what is wrong | a 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.
| Variant | Fields | Meaning |
|---|
InvalidPattern(String, Int) | what is wrong, and the character of the pattern where: counted from 0, as string.slice counts | pattern 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.