Wikipedia: Error handlingerror(value) accepts any value, not just strings. Passing a map lets you attach structured metadata — a code, a field name, or any other context.
fmt := import("fmt")
notFound := func(name) {
return error({code: 404, message: "not found: " + name})
}
result := notFound("config.json")
if is_error(result) {
e := result.value
fmt.println("code: ", e["code"])
fmt.println("message: ", e["message"])
}
validate := func(age) {
if age < 0 {
msg := "must be non-negative"
return error({field: "age", reason: msg})
}
if age > 150 {
return error({field: "age", reason: "unrealistic value"})
}
return age
}
fmt.println(validate(25))
err := validate(-1)
if is_error(err) {
fmt.println(err.value["field"] + ": " + err.value["reason"])
}
try it
code: 404 message: not found: config.json 25 age: must be non-negative