OptionError
Overview
The OptionError class is a specialized error type in the @ts-rust/std library,
used specifically with the Option type to indicate errors related to optional
value operations. It extends the AnyError class where template
T is OptionErrorKind and
provides additional context about why an Option operation failed.
When It Appears
OptionError is thrown in scenarios involving the Option type, such as
attempting to unwrap a None value using methods like unwrap() or expect().
Usage
OptionError is encountered when working with the Option type and its methods.
It helps developers identify and handle cases where an expected value is
absent (None).
Example
import { none, Option, isOptionError } from "@ts-rust/std";
// Create an Option with no value
const maybeValue: Option<number> = none();
try {
// Attempt to unwrap a None value, which throws an OptionError
const value = maybeValue.unwrap();
} catch (e) {
if (isOptionError(e)) {
console.log(e.message); // "[UnwrapCalledOnNone] `unwrap`: called on `None`."
}
}
// Using expect() with a custom message
try {
maybeValue.expect("Expected a number, but got None");
} catch (e) {
if (isOptionError(e)) {
console.log(e.message); // "[ExpectCalledOnNone] Expected a number, but got None."
}
}
OptionErrorKind Values
The OptionError class uses the OptionErrorKind enum to categorize errors. Each
value corresponds to a specific failure scenario:
| Kind | Description |
|---|---|
ValueAccessedOnNone | Thrown when the value property is accessed on a None variant. |
ExpectCalledOnNone | Thrown when expect() is called on a None variant. |
UnwrapCalledOnNone | Thrown when unwrap() is called on a None variant. |
PredicateException | Thrown when a callback/predicate passed to a method throws an exception (e.g., map, filter, unwrapOrElse, mapOrElse, match, getOrInsertWith). |