Expected failures with Result#
Use Result[T, E] when an operation succeeds with T or fails with an expected error E. E may be any value type. Most failures use the prelude type Error
. Result, ok, error, and Error are in the prelude.
Return ok(value: ...) for success and error(cause: ...) for failure. Both are ordinary values. A caller can test the Result with is_error(), read the success value with if v := x, or pass the error on with ?. Validate runtime input with ordinary conditions before doing the work.
Validate a value and show the outcome#
Save this as quantity.ms and run ms run quantity.ms:
fn quantity(value Int) Result[Int, Error] {
if value <= 0 {
return error(Error("Quantity must be positive", kind: "EINVAL"))
}
return ok(value)
}
fn show(value Int) Void {
outcome := quantity(value)
if outcome.is_error() {
print(outcome.err().message)
return
}
print(f"Quantity: {outcome.get()}")
}
fn main() Void {
show(3)
show(0)
}Quantity: 3
Quantity must be positiveBoth calls return normally. The second returns an error value, and show chooses how to present it. Use ?
when the caller should pass that error on instead.
Shorthand: T! and T!E#
T! is Result[T, Error] and T!E (with no space before E) is Result[T, E], mirroring T? for optionals. Use T!E for a failure that is not an Error. Result[T, E] stays valid. T!Error says the same as T!, so ms fmt writes it as T!.
fn parse_port(text String) Int! {
port := ok_or(text.parse_int(), Error("missing port"))?
return ok(port)
}Suffixes apply left to right: Int?! is Result[Int?, Error] and Int!? is an optional Result[Int, Error]. A function type needs parentheses first, as with ?: (fn() Int)!.
The Error type#
Error is a plain type with a fixed shape:
export type Error {
message String
kind String? = null
details Map[String, String] = Map[String, String]()
}messageis the text to show a person.kindis an optional short code a caller can branch on. It isnull(the default) when no code fits. The standard library uses POSIX errno names such as"ENOENT"(not found),"EEXIST","EACCES","EINVAL"(invalid input),"EBADMSG"(malformed data),"EOVERFLOW"(limit exceeded),"ERANGE","ENOTSUP","EBADF"(closed),"EIO","EAGAIN","EBUSY","ETIMEDOUT", and"ECANCELED"; the full list is in theErrordeclaration. Your own code may use any string, preferably with its own prefix such as"EQUOTA". A literal, or any string of at most 15 bytes, never allocates.detailsholds extra named context as text, such as a path or a line number.
Build one by calling Error(...). There is no separate constructor function and no namespace.
fn find_user(id Int) String! {
if id < 0 {
return error(Error("negative id", kind: "EINVAL"))
}
return error(Error("no such user", kind: "ENOENT", details: {"id": id.to_string()}))
}
fn describe(id Int) String {
outcome := find_user(id)
if outcome.is_ok() { return outcome.get() }
if outcome.err().kind == "ENOENT" { return f"missing {outcome.err().details["id"]}" }
return outcome.err().message.clone()
}Standard-library failures are Error values too: branch on kind, read details, and do not import a per-module error type. Two errors are equal when their three fields are equal.
Returning a domain error#
An Error fits most code. Use your own type as E when callers need typed payloads or exhaustive cases.
import Decimal from "@std/math/decimal.ms"
enum DiscountError {
InvalidPrice
InvalidPercent
}
fn discount(price, percent Decimal) Result[Decimal, DiscountError] {
if price < 0d {
return error(InvalidPrice)
}
if percent < 0d or percent > 100d {
return error(InvalidPercent)
}
return ok(price * (1d - percent / 100d))
}The function validates inputs, returns an explicit error for each failure, and wraps the result in ok.
Handling the result#
This continues the declarations above:
fn discount_message(price, percent Decimal) String {
if value := discount(price, percent) {
return f"Discounted price: {value}"
}
return "Discount could not be calculated."
}This caller discards the cause. To use it, call err() after is_error(), or propagate it with ?
.
Checking, extracting, and composing#
| Method | Behavior |
|---|---|
is_ok(), is_error() | Test the case, including successful zero, false, or Void values |
get() T | Return the successful payload; on an error, fault |
get_or(default T?) T | Return the successful payload, or default on an error |
err() E | Return the error payload; fault on success |
get_or_else(create fn(E) T) T | Return the successful payload, or call create once with the original error on failure |
or_else(create fn(move E) Result[T, E]) Result[T, E] | Take the Result: keep a success, or hand the error to create once and return its Result |
map_error[F](transform fn(move E) F) Result[T, F] | Take the Result and hand an error to transform once; preserve a success unchanged |
map[U](transform fn(move T) U) Result[U, E] | Take the Result and hand a success to transform once; preserve an error unchanged |
and_then[U](transform fn(move T) Result[U, E]) Result[U, E] | Take the Result; on success, return the callback’s Result; preserve an existing error |
map wraps the callback’s value in ok, even if it is a Result or Optional. and_then requires the same E; translate unrelated errors with ordinary functions. The four combinators move their receiver: .clone() a Result you still need.
This fragment uses discount above:
price := discount(price: 20d, percent: 10d).get_or(0d)
text := discount(price: 20d, percent: 10d).map(value => value.to_string())Callbacks run sequentially in the caller’s context; faults and cancellation propagate normally. get faults with called Result.get() on error followed by the whole error; use it only when success is established. Routine failures use a fallback, if v := x, or ?.
Converting success to an Optional#
to_optional() T? returns the original payload as a present optional, or null on error. It does not flatten the payload or turn faults or cancellation into absence.
import Decimal from "@std/math/decimal.ms"
fn successful_price(outcome Result[Decimal, Error]) Decimal? {
return outcome.to_optional()
}To turn absence into an error, use ok_or
.
Discarding a result#
A standalone call such as discount(price: 20d, percent: 10d) discards both outcomes, and the checker rejects it, including for Result[Void, E]. Handle it with if v := x, ?, or return it. To ignore it deliberately, put void in front:
void discount(price: 20d, percent: 10d)The initializer still runs and the outcome is dropped unread. Several void statements may share a scope. This does not handle an error or stop a fault.
Converting a domain error to Error#
? forwards the error type unchanged and never converts one. Translate a domain error with an ordinary function or map_error:
fn discount_error(cause DiscountError) Error {
return Error("discount failed", kind: "EINVAL")
}
fn discount_checked(price, percent Decimal) Decimal! {
return discount(price, percent).map_error(discount_error)
}Add context with wrap_error(context, cause) from @std/core.ms: error(wrap_error("read config", cause)) reports read config: <cause message>, keeps the kind and details, and stores the original message in details["cause"]. join_errors(errors) combines several errors into one Error whose message holds theirs, one per line, with a count detail (none when the list is empty).