expectations

Error handling that bundles exceptions with return values.

The design of this module is based on C++'s proposed std::expected and Rust's std::result. See "Expect the Expected" by Andrei Alexandrescu for further background.

Members

Classes

Unexpected
class Unexpected(T)

An exception that represents an error value.

Functions

expected
Expected!(T, E) expected(T value)

Creates an Expected object from an expected value, with type inference.

missing
Expected!(T, E) missing(E err)

Creates an Expected object from an error value.

Structs

Expected
struct Expected(T, E = Exception)

An Expected!(T, E) contains either an expected value of type T, or an error value of type E explaining why the expected value couldn't be produced.

Templates

flatMap
template flatMap(alias fun)

Forwards the expected value in an Expected object to a function that returns an Expected result.

map
template map(alias fun)

Applies a function to the expected value in an Expected object.

Examples

1 import std.exception: assertThrown;
2 
3 Expected!int charToDigit(char c)
4 {
5     int d = c - '0';
6     if (d >= 0 && d < 10) {
7         return expected(d);
8     } else {
9         return missing!int(
10             new Exception(c ~ " is not a valid digit")
11         );
12     }
13 }
14 
15 auto goodResult = charToDigit('7');
16 auto badResult = charToDigit('&');
17 
18 assert(goodResult.hasValue);
19 assert(goodResult.value == 7);
20 
21 assert(!badResult.hasValue);
22 assertThrown(badResult.value);
23 assert(badResult.error.msg == "& is not a valid digit");

Meta

Authors

Paul Backus