Learn the language Browse docs
On this page 7 sections

Learn the language

Results

How a function reports failure with result, how try and catch unwrap it, and how ok and err differ between values and routes.

This page shows how to write a function that can fail and how the caller handles the failure. A function that can fail returns a result: either a success value or an error. The caller unwraps it with try and catch. There are no exceptions. A result is an ordinary value you bind, pass, and unwrap. Run each snapshot below. The exit code is the answer.

30 seconds — ok(41) unwraps to 41, plus 1 is 42. The happy path, exiting 42.

Program
fn load_value() -> result {
    val value: result = ok(41)
    return value
}

fn read_value() -> int {
    val value: int = try load_value() catch {
        return 0
    }
    return value
}

fn main() -> int {
    return read_value() + 1
}
Run
./orbit build read.orb -o read
./read
echo $?   # 42

Exit 42

A function that can fail returns result

Build a success with ok(value) and a failure with err(message, code). ok(v) carries a value. err(message, code) carries a message and a numeric code; the code is optional and defaults to 500. ok takes exactly one value, and ok() is E1003. A -> result function whose body returns a plain int is a type mismatch (Return type mismatch: expected result, got int):

resultvals.orb
fn load_value() -> result {
  val value: result = ok(41)
  return value
}

fn reject_value() -> result {
  val failure: result = err("invalid input", 7)
  return failure
}

A result can be bound to a val, with or without an annotation, and passed to a function as an argument. result is a builtin type, not a std module. ok and err are keywords. There is nothing to import; a result module never existed.

resultarg.orb
fn unwrap(r: result) -> int {
  val value: int = try r catch {
      return 0
  }
  return value
}

fn read_twice() -> int {
  val bound = load_value()
  return unwrap(bound) + unwrap(load_value())
}

Values are not routes

ok and err are used in two different ways. With parentheses in an expression, ok(...) and err(...) build result values. Inside a route, return ok 200 … and err 400 … are HTTP response forms (a route is an HTTP endpoint). Same words, different constructs. In a route, ok with a 4xx/5xx status is rejected at check time (use err for failures), and err with a 2xx/3xx status is rejected the same way:

routesforms.orb
route GET "/health" {
  return ok { status: "UP", uptime_seconds: system.uptime() }
}

route GET "/private" {
  err 401 "unauthorized"
}

The shared spelling causes a parsing trap (known as STAB-9): a bare return ok(...) inside a function returning result is read as a route response, not as a value. The fix is the bind-first rule: put the value in a val first, then return the val:

bindfirst.orb
fn load_value() -> result {
  val value: result = ok(41)   // bind first…
  return value                 // …then return the binding
}

// NOT this: bare "return ok(41)" parses as the route form (STAB-9).

Step through the three spellings. The same words end up as a value, an HTTP response, or a compile error:

orbit
val value: result = ok(41)
return value

Expression ok(...) builds an ordinary result value: bind it, pass it, unwrap it with try.

Kind result value

Try and catch

try unwraps a result. On success it gives you the value. On failure it runs the catch block, which can run statements and return from the enclosing function. Here read_value() returns 0 when load_value() fails:

trycatch.orb
fn read_value() -> int {
  val value: int = try load_value() catch {
      return 0
  }
  return value
}

try also works on a result parameter, as the pass-it-along example shows: try r catch { return 0 } where r: result. One combination is untested: passing a result as an argument and catching it inside the callee in one assertion helper. The test suite notes it as untested rather than asserting it.

Catch can read the error

Put a name after catch and it holds the error message:

catche.orb
fn read_value() -> int {
  val value: int = try load_value() catch e {
      print(e)
      return 0
  }
  return value
}

e is the message from err(message, code), a string you can print, measure, or compare. The third snapshot above uses e.len() as the exit code: "empty input" is 11 characters, so it exits 11.

When catch does not return

If a catch block does not return, execution continues on the line after the try. That makes catch a place to recover: set a default and carry on.

recover.orb
fn read_or_default(text: string) -> int {
  var mut fallback: int = 0
  val value: int = try parse(text) catch {
      fallback = -1
  }
  return value + fallback
}

When parse succeeds, value is the unwrapped payload and fallback stays 0. When it fails, the handler sets fallback to -1, and execution continues on the line after the try. Only the branch that runs has effects, the same rule as if as a value.

Do not discard a result

A call that can fail reports its failure only through the value, and nothing in the runtime logs it. A statement whose type is result and whose answer nothing reads is E1010, because the program would exit 0 while the write, fetch or parse did not happen:

discarded.orb
extern fn orbit_file_read(path: string) -> result

fn main() -> int {
  orbit_file_read("notes.txt")   // error: The result of 'orbit_file_read' is discarded
  return 0
}

Bind it with val r = … and read it with try r catch, match on it, or return it from a -> result function. The last statement of an if branch or a match case is that branch’s value, so val r = if c { ok(1) } else { err("x") } is accepted.

Do not name a function read, write, open, or close

A function called read, write, open, or close collides with the C library function of the same name. The checker now refuses it (verified in compiler/front/sema.orb on main): 'read' is a C library function name and cannot be used as an Orbit function name; rename it. The same list covers other libc names such as strlen, malloc, exit, remove and socket.

What next

Next: routes turns these functions into HTTP endpoints. The full specification is the language reference.

Type to search commands, errors, modules and concepts.