Errors
Ant has two ways to fail. A failure the caller is meant to handle, such as bad input or a missing file, is a value: a function returns a Result, Ok with its value or Err with its error. A bug or an impossible state is a panic: panic or a failed assert stops the goroutine. If the program can recover by doing something else, return a Result; if the only fix is to change the code, panic.
The standard library's error type is Error, a record with a message. An error that code branches on is a type of its own, often a tagged union such as EmptyInput | BadDigit: build it with Result.err, and turn it into an Error with Result.mapErr when a person is to read it.
try reads a result inside a function: it gives the value of an Ok and passes an Err up to the caller. Each caller that knows more adds context in front of the message with Result.wrapErr, so the final text says what the program was doing. A wrapErr stage goes in parentheses together with the call it wraps:
type Address = { host: string, port: int }
func parsePort(s: string): Result[int, Error] {
let n = s.toInt() ?? return Result.fail("${s} is not a number")
if n < 1 || n > 65535 {
return Result.fail("${n} is out of range")
}
Result.ok(n)
}
func parseAddress(s: string): Result[Address, Error] {
let cut = s.cut(":") ?? return Result.fail("${s} has no port")
let port = try (parsePort(cut.after) | Result.wrapErr("parse address ${s}"))
Result.ok(Address{ host: cut.before, port })
}
for s in ["localhost:8080", "localhost", "localhost:http", "localhost:70000"] {
let r = parseAddress(s)
println(if r is Ok { "${r.value.host} port ${r.value.port}" } else { r.error.message })
}localhost port 8080
localhost has no port
parse address localhost:http: http is not a number
parse address localhost:70000: 70000 is out of rangeA panic carries only a message and a trace. Panic.catch stops one at the edge of a unit of work, such as a job or a request, so that a bug in one does not end the others:
func percent(part: int, whole: int): int {
assert(whole > 0, "callers pass a nonempty total")
part * 100 / whole
}
for whole in [8, 0] {
let r = Panic.catch({ percent(2, whole) })
println(if r is Ok { "${r.value}%" } else { "bug: ${r.error.message}" })
}25%
bug: assertion failed: whole > 0 (0 > 0): callers pass a nonempty totalFunctions by job
Building a result
- Result.ok: an
Okcarrying a value - Result.err: an
Errcarrying an error of any type - Result.fail: an
Errcarrying anErrorwith a message; only where the error type isErroritself, so under a wider error type useResult.err
Reading a result
- try: the value of an
Ok, or return theErrto the caller - is: tell
OkfromErr, then read.valueor.error - Result.isOk: whether a result is an
Ok - Result.unwrap: the value, or a panic on an
Err - Result.unwrapOr: the value, or a fallback on an
Err
Transforming a result
- Result.map: apply a function to the value of an
Ok - Result.mapErr: apply a function to the error of an
Err, such as to widen its type or turn it into anError
Combining results
- Result.all:
Okof every value, or the firstErr
Adding context
- Error: the library's error, a record with a
message - Error.wrap: a new
Errorwith context in front of the message - Result.wrapErr: wrap the error of an
Err, and keep anOkas it is
Panicking
- panic: stop the goroutine with a message
- assert: panic when a condition is false, showing the values it read
Catching a panic
- Panic.catch: call a function and return
Okof its value, orErrof the panic that left it - Panic.raise: panic again with a caught panic's message and trace
- Panic: a caught panic, its message and trace
- Panic.Frame: one frame of a trace
Cleaning up
- defer: run a block when the enclosing block exits, however it exits, a panic or an error passed on with
tryincluded
See also
- Errors: how
Result,panic,assert,defer, andPanic.catchfit together - Tour: errors and Tour: panics
