Docs · Language

The error model

A failure in Vyi is a value in the return type. Absence is ?T, and an error or a value is E!T. Both are ordinary enums, handled with match, try, and catch. This page states the type forms, error-type inference, the rules for try and catch, error declarations, error messages, and what main returns. Guide 07, Optionals and errors introduces them. Panics are a separate channel, outside every signature (errors and panics).

Optional and Result are ordinary enums

Both are generic enums declared in @core, visible in every file without an import:

TypeDeclarationVariants
Optional(T)enum { None, Some(T) }None, Some(T)
Result(E, T)enum { Ok(T), Err(E) }Ok(T), Err(E)

You match over them, destructure them in if bindings, nest them, and store them in fields like any enum. Some, None, Ok, and Err are ordinary variant names, found by the expected type like every enum's variants. A generic type with the same arguments is the same type, so ?i32 and Optional(i32) are one type:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con port: Optional(i32) = Some(8080)
    con same: ?i32 = port
    if Some(p) = same {
        println(p)   // prints 8080
    }
    return Ok(0)
}

The language treats them specially in two places only: the type spellings below, and the try and catch operators.

Type spellings

SpellingMeansHolds
?TOptional(T)a T, or nothing
E!TResult(E, T)a T, or an error of type E
(A | B)!TResult(A | B, T)a T, or an error of either type
!TResult(_, T)a T, or an error whose type is inferred
E!()Result(E, ())nothing on success, or an error of type E
!Result(_, ())nothing on success, or an inferred error

Any type can be an error type: an enum, a struct, a union, an error declaration. The error travels in the Err payload as a value: an error return is an ordinary return, with no allocation and no unwinding.

A missing success type is (), the empty tuple, and success is written Ok(()). A try as a statement propagates a failure and discards the success value:

Vyi
import { println } from "@fmt"

enum SaveError { DiskFull }

fn save(spaceLeft: i32) SaveError!() {
    if spaceLeft == 0 { return Err(DiskFull) }
    return Ok(())
}

fn backup(spaceLeft: i32) ! {
    try save(spaceLeft)
    return Ok(())
}

fn main() !u8 {
    backup(0) catch {
        println("not saved")   // prints not saved
    }
    return Ok(0)
}

Inferred error types

The _ in Result(_, T) is solved for each function from that function's own body, never from its callers.

  1. Each return Err(e) adds the type of e.
  2. Each try adds the whole error type of its operand.
  3. The result is the smallest union of the added types: one type gives that type, several give their union, and duplicates collapse.
  4. A body that adds nothing has the empty error type: the result is always Ok. try and catch on it still compile, and the failure path never runs.
  5. Functions that try themselves or each other have error types that depend on each other. They are worked out together: starting from empty, each round adds what the bodies contribute until nothing new arrives. A function on such a cycle that never produces an error has the empty type. An error type that would contain itself (an error that carries the function's own result) never settles, and must be written.
Vyi
import { println } from "@fmt"

enum NetError { Down }
enum IoError { Closed }

fn read(fd: i32) !i32 {   // IoError
    if fd == 0 { return Err(IoError.Closed) }
    return Ok(fd)
}

fn load(fd: i32) !i32 {   // NetError | IoError
    if fd < 0 { return Err(NetError.Down) }
    con size = try read(fd)
    return Ok(size)
}

fn main() !u8 {
    match load(0) {
        Ok(size):         println(size),
        Err(_: NetError): println("network down"),
        Err(_: IoError):  println("closed"),   // prints closed
    }
    return Ok(0)
}

With no expected enum to look in, the Err arguments above name their enum, IoError.Closed. An arm narrowed to one member of an inferred union is described in patterns.

A narrower error type converts to a wider one: a function declared (NetError | ParseError)!T can try a call whose error type is NetError. The reverse is an error (try).

A function type has no body, so !T in a function type cannot be inferred. Write the error type:

Vyi · does not compile
fn run(task: fn() !i32) i32 {   // error: cannot infer error type
    return task() catch 0
}

try

try expr gives the operand's success value. On failure it returns the failure from the enclosing function at that point. It may stand as a statement (propagate, discard the success) or inside any expression (return Ok(try f(x))).

The operand is an Optional or a Result, and what try returns must fit the enclosing function's own failure channel:

OperandEnclosing function returnsResult
E!TF!U, where E is F or a member of itthe Err propagates, converted to F
E!TF!U, where E is not part of Ferror: the operand's error type does not match
?T?UNone propagates
?TE!Uerror: a None carries no error
E!T?Uerror: an Err cannot become None
eithera type that cannot failerror

The messages:

CaseMessage begins
an optional in a function returning a Result`invalid try: cannot propagate an optional through an error-returning function`
a Result in a function returning an optional`invalid try: cannot propagate an error through an optional-returning function`
an operand that cannot fail`invalid try: the operand is not fallible (it is i32, not an error union or optional)`
a function that cannot fail`invalid try: the enclosing function does not return an error union or optional`
a wider error type into a narrower one`invalid try: the operand's error type A | B does not match the enclosing function's A`
Vyi · does not compile
enum LookupError { Missing }

fn find(id: i32) ?i32 {
    if id == 0 { return None }
    return Some(id)
}

fn get(id: i32) LookupError!i32 {
    con v = try find(id)   // error: invalid `try`: cannot propagate an optional through an error-returning function
    return Ok(v)
}

Moving a failure between channels is a decision (which error a missing value becomes, or what an error means where only absence is expected), so you write it with catch.

catch

expr catch fallback gives the operand's success value, or on failure the fallback. The whole expression has the plain success type T. The fallback takes one of four forms:

FormWrittenGives on failure
expressionexpr catch 0the expression; a lone value needs no braces
blockexpr catch { ... }the block's last expression, or the block leaves with return, break, continue, or panic
functionexpr catch onErroronError(e), called with the Err payload
arrow functionexpr catch (e: E) T => bodythe arrow's result

On an Optional the same forms apply. A None carries nothing, so a function after catch takes no parameters. When the success type is (), a block after catch runs only for its effect.

Vyi
import { println } from "@fmt"

enum MathError { DivByZero, Overflow }

fn div(a: i32, b: i32) MathError!i32 {
    if b == 0 { return Err(DivByZero) }
    return Ok(a / b)
}

fn onError(e: MathError) i32 {
    return match e {
        DivByZero: -1,
        Overflow:  -2,
    }
}

fn find(id: i32) ?i32 {
    if id == 0 { return None }
    return Some(id)
}

fn guest() i32 { return 100 }

fn main() !u8 {
    println(div(40, 4) catch 0)                       // prints 10
    println(div(9, 0) catch onError)                  // prints -1
    println(div(9, 0) catch (e: MathError) i32 => 7)  // prints 7
    println(find(0) catch guest)                      // prints 100
    return Ok(0)
}

The operand is an Optional or a Result; anything else has no failure to handle:

Vyi · does not compile
fn total() i32 { return 3 }

fn main() !u8 {
    con n = total() catch 0   // error: invalid `catch`: the operand is not fallible
    return Ok(0)
}

A catch block that returns moves a failure from one channel to the other, in either direction:

Vyi
import { println } from "@fmt"

enum LookupError { Missing }

fn find(id: i32) ?i32 {
    if id == 0 { return None }
    return Some(id)
}

fn get(id: i32) LookupError!i32 {
    con v = find(id) catch { return Err(Missing) }
    return Ok(v)
}

fn maybe(id: i32) ?i32 {
    con v = get(id) catch { return None }
    return Some(v)
}

fn main() !u8 {
    if Err(Missing) = get(0) {
        println("missing")   // prints missing
    }
    println(maybe(0) == None)   // prints true
    return Ok(0)
}

Overloads don't differ by failure

Overloads differ in their parameter types, never only in the result type, so fn parse(s: [*con]u8) i32 beside fn parse(s: [*con]u8) ParseError!i32 is a duplicate declaration. To choose the result type at the call, take it as a known T: type parameter (known values).

Variants need an expected type

A bare variant name (Some, None, Ok, Err, and every variant of every enum) is looked up in the enum the surrounding code expects:

PositionExample
a returnreturn Err(e) in an E!T function
a call argumentf(Some(3)) where the parameter is ?i32
an annotated bindingcon o: ?i32 = Some(5)
an assignmentslot = None where slot: ?*mut i32
a match arm or if bindingSome(v): ..., if Ok(v) = r { ... }
the other side of ==c == Red where c: Color
a constructor's payloadErr(Empty): Empty is looked up in Err's payload type

The expected type reaches inward: in return Err(Empty), Err is found in the function's result type, and Empty in Err's payload type. With no expected type there is nothing to look in, and the compiler reports `cannot infer enum constructor type from the surrounding code` (for a bare None, `cannot infer enum variant type). Name the enum (Color.Red`) or give the binding a type:

Vyi · does not compile
fn main() !u8 {
    con port = Some(8080)   // error: cannot infer enum constructor type from the surrounding code
    return Ok(0)
}

error declarations

An error declaration declares error members, each with a message. It has two forms:

Vyi
import { println } from "@fmt"

error DiskFull "disk is full"

error ParseError {
    Unexpected "unexpected token";
    Eof "end of input";
}

fn parseBool(s: [*con]u8) ParseError!bool {
    if s.len == 0 { return Err(Eof) }
    if s == "true" { return Ok(true) }
    if s == "false" { return Ok(false) }
    return Err(Unexpected)
}

fn main() !u8 {
    if Err(Eof) = parseBool("") {
        println("empty")   // prints empty
    }
    return Ok(0)
}
FormDeclaresWritten
error DiskFull "disk is full"one member, named for the declarationDiskFull
error ParseError { Unexpected "..."; Eof "..."; }a type with several members, separated by ;ParseError.Eof, or Eof where the expected type is ParseError

A member carries its message and nothing else; it holds no data. For an error that carries data, use an enum or a struct with @errmsg. When a member reaches the end of main, the program prints its message with no method to write. The standard library declares OutOfMemory (@mem) and ReadError and WriteError (@io) this way.

The open error type: error

error alone is a type: the open error type. A member of any error declaration converts to it, so a function returning error!T can fail with members of any declaration, including ones it has never seen. A value of type error holds which member it is and carries no payload.

A match over an error names a single-form member by its name and a block member by its path. Each name is resolved by scope, as any name is. No list of arms covers an open set, so the match needs a default arm.

Vyi
import { println } from "@fmt"

error DiskFull "disk is full"

error ParseError {
    Unexpected "unexpected token";
    Eof "end of input";
}

fn save(text: [*con]u8) error!() {
    if text.len == 0 { return Err(ParseError.Eof) }
    if text.len > 5 { return Err(DiskFull) }
    return Ok(())
}

fn describe(e: error) [*con]u8 {
    return match e {
        DiskFull:       "no space",
        ParseError.Eof: "nothing to save",
        default:        "something else",
    }
}

fn main() !u8 {
    if Err(e) = save("a long text") {
        println(describe(e))   // prints no space
    }
    return Ok(0)
}
Vyi · does not compile
error DiskFull "disk is full"

fn describe(e: error) [*con]u8 {
    return match e {   // error: a `match` over error needs a `default` arm
        DiskFull: "no space",
    }
}

Error messages: @errmsg

Any type can be an error; there is no base type and no registration. Two methods give an error behavior:

MethodDeclared asRole
@errmsgfn (e: E) @errmsg() [*con]u8the message; printed when the error reaches the end of main
@errstackfn (e: *con E) @errstack() *con ErrStackthe call stack the error recorded, if its type keeps one
Vyi
import { println } from "@fmt"

enum MathError { DivByZero }

fn (e: MathError) @errmsg() [*con]u8 {
    return "division by zero"
}

fn div(a: i32, b: i32) MathError!i32 {
    if b == 0 { return Err(DivByZero) }
    return Ok(a / b)
}

fn main() !u8 {
    if Err(e) = div(1, 0) {
        println(e.@errmsg())   // prints division by zero
    }
    return Ok(0)
}

An error from an inferred union of several types has a union type, and e.@errmsg() on it calls the method of whichever member it holds. Every member must declare it (union receivers).

Errors with a call stack: @errors

ExportTypeNotes
Errorstruct { msg: [*con]u8, stack: ErrStack }declares @errmsg and @errstack
Error.new(msg)fn (Error) new(msg: [*con]u8) Errorrecords the call stack where it is called
ErrStacka fixed-capacity list of framesholds up to 32 calls; recording allocates nothing; when there are more, it keeps the innermost
capture(skip)fn capture(skip: i32) ErrStackrecords the stack directly, leaving out the skip innermost frames

The stack is recorded when the error is built, not when it is passed on: by the time an Err has gone up through several trys, the calls that explain it have returned. Each frame has a file, line, and col, oldest first.

Vyi
import { println } from "@fmt"
import { Error } from "@errors"

fn open(name: [*con]u8) Error!i32 {
    return Err(Error.new("file not found"))
}

fn main() !u8 {
    if Err(e) = open("config") {
        println(e.@errmsg())         // prints file not found
        println(e.@errstack().len)   // prints 1
    }
    return Ok(0)
}

main

The entry point is fn main() !u8. Its error type may be inferred (!u8) or written (BootError!u8). Any other signature is an error:

Vyi · does not compile
fn main() u8 {   // error: main must be `fn main() !u8`
    return 0
}
main returnsThe program
Ok(n)exits with status n
Err(e)prints error: and the error's message on standard error, and exits with status 1. The message is an error member's own text or what @errmsg returns; an error type with neither prints error: alone
Vyi
error NoConfig "config file missing"

fn readConfig() NoConfig!u8 {
    return Err(NoConfig)
}

fn main() !u8 {
    con level = try readConfig()
    return Ok(level)
}

This program prints error: config file missing on standard error and exits with status 1.

Errors and panics

A function's errors are part of its return type, so its signature says whether a call can fail: a function that returns i32 always gives back an i32.

A panic is not an error value and appears in no signature: an index out of bounds, a division by zero, an explicit panic(...). It stops the program with its reason and a stack trace, and exit status 101, unless a recover catches it (statements, guide 08). Which one a function uses is its choice: an allocator's new returns OutOfMemory as an error, while Vec.push returns nothing and panics when it cannot get memory.

See also: guide 07, Optionals and errors, types, and @core.