Error Handling
Report failure in the ways the language offers, and release a resource whichever way the work using it ends.
Adapted from Exercism’s problem specification (MIT). Listed under Parsing & Validation.
// FILE: error_handling.nomi
//# The ways a Nomi function says it could not do its job: `None` for an
//# answer that is not there, an `Err` for a failure the caller handles, and
//# a trap for a promise the caller broke. And how a resource is released
//# whichever way the work ends: `defer`.
import std::io.{self, Reader}
/// Why a total could not be read.
pub enum Error
NotANumber {text: String}
Io io.Error
end
/// The number `text` writes, or `None` when it writes none.
pub fn number(text: String) -> Maybe<Int>
String.to_int(text)
end
/// The number `text` writes, or an `Err` saying what was there instead.
pub fn parse(text: String) -> Result<Int, Error>
Maybe.to_result(number(text), .NotANumber{text:})
end
/// The number `text` writes. The caller promises it writes one, and a
/// `text` that does not is a bug in the caller: the call traps.
pub fn parse_trusted(text: String) -> Int
number(text)!
end
/// The sum of the numbers on the lines of `reader`, or the first line that
/// is not one. The reader is closed when the sum is read, whether or not
/// it could be.
pub fn sum_lines(reader: Reader) -> Result<Int, Error>
defer Reader.close_quietly(reader)
total(reader, parse)
end
/// The sum of the numbers on the lines of `reader`, each of which the
/// caller promises is a number. The reader is closed when the sum is read,
/// and when a line breaks the promise and the call traps.
pub fn sum_trusted_lines(reader: Reader) -> Result<Int, Error>
defer Reader.close_quietly(reader)
total(reader, fn line -> Ok(parse_trusted(line)))
end
/// The sum of what `read` makes of each line still in `reader`.
fn total(reader: Reader, read: (String) -> Result<Int, Error>) -> Result<Int, Error>
next = Reader.read_line(reader) |> Result.map_err(Error.Io)
case next?
None -> Ok(0)
Some(line) -> Ok(read(line)? + total(reader, read)?)
end
end
// FILE: error_handling_test.nomi
import
std::io.{self, Reader}
std::tasks.Task
error_handling
end
/// Whether `reader` has been closed: reading from it again is refused.
fn is_closed(reader: Reader) -> Bool
Reader.read_line(reader) == Err(io.Error.Closed)
end
test "a missing answer is None"
assert error_handling.number("1") == Some(1)
assert error_handling.number("a") == None
end
test "a failure the caller handles is an Err"
assert error_handling.parse("1") == Ok(1)
assert error_handling.parse("a") == Err(.NotANumber{text: "a"})
end
test "a broken promise traps"
outcome = concurrent
task = Task.spawn(fn -> error_handling.parse_trusted("a"))
Task.outcome(task)
end
assert .Failed(_) = outcome
end
test "a resource is released when the work succeeds"
reader = Reader.from_text("1\n2\n3\n")
assert error_handling.sum_lines(reader) == Ok(6)
assert is_closed(reader)
end
test "a resource is released when the work fails"
reader = Reader.from_text("1\nx\n3\n")
assert error_handling.sum_lines(reader) == Err(.NotANumber{text: "x"})
assert is_closed(reader)
end
test "a resource is released when the work traps"
reader = Reader.from_text("1\nx\n3\n")
outcome = concurrent
task = Task.spawn(fn -> error_handling.sum_trusted_lines(reader))
Task.outcome(task)
end
assert .Failed(_) = outcome
assert is_closed(reader)
endok a missing answer is None
ok a failure the caller handles is an Err
ok a broken promise traps
ok a resource is released when the work succeeds
ok a resource is released when the work fails
ok a resource is released when the work traps
test result: ok. 6 passed, 0 failed
How it’s written
Section titled “How it’s written”- Adapted: the exercise has no canonical data; each track sets its own tests, and most ask for an exception to be thrown and caught, a “none” result, a success-or-failure result, and a file-like object closed on success and on an exception. Nomi has no exceptions, and a trap is never caught inside the program. This port keeps the tests’ shape, after the Python track’s five: a missing answer is
None(number), a failure the caller handles is anErr(parse), a broken promise traps (parse_trusted, seen from outside as a spawned task’sFailedoutcome), and a resource is released when the work succeeds, fails or traps. - The resource is a real one, a
std::ioReaderover text, so the tests need no fake that records being closed: reading from a closed reader is refused withio.Error.Closed, whichis_closedchecks. sum_linesandsum_trusted_linesregisterdefer Reader.close_quietly(reader)first, so the reader is closed on every way out of the function: the sum, anErrfromtotal, and a trap. Each returnstotal(...)directly; a call made while adeferis pending is an ordinary call, so the reader is closed aftertotalhas read it.- The trap is a postfix
!,number(text)!, which returns the number and stops the program withline N: `number(text)` found nothingwhen the caller’s text is not one. A test spawns the trapping call in aconcurrentblock and checksTask.outcomeis.Failed(_), the one place a program can see a trap. Errorhas its own variant for a line that is not a number and one that wraps the reader’sio.Error, sototalpassesError.IotoResult.map_err.