Working with Errors
In Conduit, error handling is not an afterthought handled with out-of-band exceptions. Errors are first-class domain values that compose cleanly with the type system.
This guide outlines recommended architectural patterns for designing and handling errors in production Conduit applications.
1. Model Domain Errors Explicitly
Avoid using generic string error codes or untyped error payloads. Instead, declare distinct error records for each failure domain:
export error ValidationError {
field: String
detail: String
}
export error ParseError {
input: String
}By declaring concrete fields (such as field and detail), callers can inspect error causes programmatically rather than attempting to parse brittle error message strings.
2. Decide When to Propagate vs. When to Handle
Conduit gives you two complementary tools for handling errors:
- Use
?(Try Operator): When the current function cannot reasonably resolve the failure and must forward it to its caller. - Use
switch(Pattern Matching): At boundary layers (such as HTTP handlers, CLI commands, or UI controllers) where you must resolve failures and convert them into user-facing output or fallback behavior.
func process_input(s: String) -> Int | ValidationError | ParseError {
// Propagate early to the caller if parsing fails:
val := parse_positive_int(s)?
return val * 2
}3. Handling Fallible Operations in Collections
Because map preserves errors as elements in the resulting list, processing a collection of inputs produces a list of union values: [Int | ValidationError | ParseError].
You can iterate through the list with a for loop and dispatch results with switch:
for item in results {
switch item {
case Int(val):
print("Successfully processed value")
case ValidationError(ve):
print("Validation error: " + ve.detail)
case ParseError(pe):
print("Parse error: " + pe.input)
}
}Complete Runnable Recipe
error InputError {
detail: String
}
func parse_positive(s: String) -> Int | InputError | ParseError {
guard s.len() > 0 else {
return InputError(detail: "empty string")
}
return s.to_int()?
}
func process_input(s: String) -> Int | InputError | ParseError {
val := parse_positive(s)?
return val * 2
}
func main() -> Void {
for raw in ["42", "", "unknown"] {
switch process_input(raw) {
case Int(v): print("Processed integer: {v}")
case InputError(e): print("Input error: {e.detail}")
case ParseError(e): print("Could not parse: {e.value}")
}
}
}Running the Recipe
conduit run error_recipe.cdtOutput:
Processed integer: 84
Input error: empty string
Could not parse: unknown