Skip to content

handling errors ​

A function that can fail either throws an exception or returns a Result[T, E]. Return a Result when failure is one of the outcomes the caller has to deal with, such as input that doesn't parse or a setting that isn't there. Throw when the failure is something no caller nearby can act on. Exceptions, throw and try are covered in control flow.

Result ​

Ghul.Result[T, E] is a union in the runtime library:

ghul
union Result[T, E] is
    OK(value: T) default
    ERROR(error: E)
si

OK holds the value the operation produced, and ERROR holds what it failed with. use Ghul.Result brings it into scope. A function returns Result.OK(value) or Result.ERROR(error), and the type arguments of each come from the function's return type.

OK is the union's default variant, so the operators that read an optional's value read a Result's value in the same way:

  • r? is true when r holds OK. Inside if r?, r is narrowed to OK, so r.value reads the value directly.
  • r ?? d gives the value, or d when r holds ERROR.
  • r?.m reads the member m of the value. The result is a Result holding the member, and an ERROR is passed on unchanged.
  • r! gives the value, and throws when r holds ERROR.

case, if let and isa read either variant by name:

ghul
parse_port(text: string) -> Result[int, string] is
let port: int mut
if !int.try_parse(text, port ref) then
return Result.ERROR("not a number: {text}")
elif port < 1 \/ port > 65535 then
return Result.ERROR("out of range: {port}")
fi
return Result.OK(port)
si
for text in ["8080", "99999", "http"] do
let port = parse_port(text)
// case reads either variant
let described =
case ►port
when ok: Result.OK then "port {ok.value}"
when failed: Result.ERROR then "rejected, {failed.error}"
esac
// ? asks whether it holds OK, ?? gives the value or a fallback, and ?.
// reads a member of the value, here its hexadecimal text
write_line("{text}: {described}; {port?}, {port ?? 80}, {port?.to_string("X4") ?? "-"}")
od
// ! gives the value, and throws if the result holds ERROR
write_line("{parse_port("443")! + 1}")

A discarded Result is a warning, discarded-must-use, because its failure would go unseen. Read it with one of the forms above, or write let _ = expr where it is ignored on purpose.

returning an error with ! ​

Inside a function that returns a Result, ! on a Result with the same error type returns the ERROR from the function, instead of throwing. The rest of the function runs only with values that succeeded, so a sequence of steps that can each fail reads as straight-line code. This needs an error type that implements Ghul.Error. A union of the failures a part of the program can produce is the usual choice:

ghul
union ConfigError: Ghul.Error is
MISSING(key: string)
BAD_PORT(text: string)
si
port_number(text: string) -> Result[int, ConfigError] is
let port: int mut
return if int.try_parse(text, port ref) then Result.OK(port) else Result.ERROR(ConfigError.BAD_PORT(text)) fi
si
// each ! gives an OK's value, or returns the ERROR from address at once
address(host_key: string, port_key: string) -> Result[string, ConfigError] is
let host = lookup(host_key)!
let port = port_number(lookup(port_key)!)!
return Result.OK("{host}:{port}")
si
write_line("{address("host", "port")}")
write_line("{address("host", "timeout")}")
write_line("{address("server", "port")}")

Ghul.Error has one member, message, which gives the error's text unless the type declares its own. Anywhere else, a failed ! throws: a Ghul.ErrorException holding the error when its type implements Ghul.Error, and a Ghul.UnwrapFailedException otherwise. string doesn't implement Ghul.Error, so ! on a Result[int, string] throws wherever it is written.

keeping a result with &|> ​

r &|> f() passes the value in an OK to f, and wraps what f returns in OK, at the type f returns. A Result holding ERROR skips the call, including its arguments, and is passed on unchanged. When f returns a Result itself, that is the result, so a chain of &|> stages stops at the first call that fails. The chain is still a Result, so it can be stored, returned, or ended with ??:

ghul
for text in ["21", "-4", "many"] do
let count = read_count(text)
write_line("{text}: {count ?? 0}, {count &|> twice()}, {count &|> checked() &|> twice()}")
od

converting an error with ||> ​

r ||> f() is the mirror of &|>: it passes the error in an ERROR to f, and wraps what f returns in ERROR. A Result holding OK skips the call. Use it to turn one error type into another, typically to turn the errors of a lower layer into the errors of the code calling it. When f returns a Result, that is the result, so load(path) ||> load_backup() calls load_backup only when load fails.

Write ! after the call to convert the error and return it from the function in one step. When r holds OK, r ||> f()! gives the value and builds nothing:

ghul
// the error is converted, and the value stays a Result:
counted(text: string) -> Result[int, InputError] => read_count(text) ||> to_input_error()
// the error is converted and returned, and the value is unwrapped:
total(a: string, b: string) -> Result[int, InputError] is
let x = read_count(a) ||> to_input_error()!
let y = read_count(b) ||> to_input_error()!
return Result.OK(x + y)
si
write_line("{counted("7")}")
write_line("{counted("seven")}")
write_line("{total("3", "4")}")
write_line("{total("3", "four")}")

?, !, ??, ?., &|> and ||> work in the same way on a union of your own that has a default variant: see option-shaped unions. The three thread-first operators are compared in functional programming.