Skip to content

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)
end
  • 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 an Err (parse), a broken promise traps (parse_trusted, seen from outside as a spawned task’s Failed outcome), and a resource is released when the work succeeds, fails or traps.
  • The resource is a real one, a std::io Reader over text, so the tests need no fake that records being closed: reading from a closed reader is refused with io.Error.Closed, which is_closed checks.
  • sum_lines and sum_trusted_lines register defer Reader.close_quietly(reader) first, so the reader is closed on every way out of the function: the sum, an Err from total, and a trap. Each returns total(...) directly; a call made while a defer is pending is an ordinary call, so the reader is closed after total has read it.
  • The trap is a postfix !, number(text)!, which returns the number and stops the program with line N: `number(text)` found nothing when the caller’s text is not one. A test spawns the trapping call in a concurrent block and checks Task.outcome is .Failed(_), the one place a program can see a trap.
  • Error has its own variant for a line that is not a number and one that wraps the reader’s io.Error, so total passes Error.Io to Result.map_err.