iyi

Playground · Methods and traits · 27 of 33

errors

Errors are values. A function that can fail says so in its type.

samples/tour/errors.iyi · errors.wasm · 156 KB
# Errors are values. A function that can fail says so in its type.

struct NotFound
  def initialize(@key : String)
  end

  def key : String
    @key
  end
end

# `Error` is a trait the compiler knows. Implementing it makes a type an
# error member wherever it appears in a union.
impl Error for NotFound
  def message : String
    "no such key: #{key}"
  end
end

STORE = {"name" => "iyi", "year" => "2026"}

def fetch(key : String) : String | NotFound
  STORE[key]? || NotFound.new(key)
end

# `!` propagates: a good value continues, an error returns from here.
def year_plus_one : Int32 | NotFound
  text = fetch("year")!
  text.to_i + 1
end

puts year_plus_one

# Handle with `case`, or fall back with `.or`, or insist with `.or_panic`.
case fetch("missing")
in String   then puts it
in NotFound then puts it.message
end

puts fetch("missing").or("default")
puts fetch("name").or_panic
output
Press Run.

recorded with iyi 0.18.0 (built on Crystal 1.22.0-dev [2a9653052] (2026-10-18)) · Linux 7.0.0-38-generic x86_64, QEMU Virtual CPU version 2.5+ · 2026-10-19

You can type in the pane: nothing here compiles, so what you type cannot run, and the page says which bytes it is running the moment the text stops being the recorded file. There is no standard input, no filesystem and no threads on this target, and one sample fails on purpose for exactly that reason.

Run executes errors.wasm, the module the compiler built from this file, in your browser. How this works

Try it on your machine

Copy the program into errors.iyi, change something, and run it. Only a compiler on your own machine can run what you wrote.

sh, after installing
$ iyi run errors.iyi