Aggregate Field Errors with errors.Join
Collect every invalid signup field with errors.Join, then inspect the combined error using errors.As and Unwrap.
Code
package main
import (
"errors"
"fmt"
"strings"
)
type FieldError struct {
Field string
Rule string
}
func (err FieldError) Error() string {
return err.Field + ": " + err.Rule
}
type Signup struct {
Email string
Age int
}
type multiError interface {
Unwrap() []error
}
func validate(signup Signup) error {
var problems []error
if !strings.Contains(signup.Email, "@") {
problems = append(problems, FieldError{Field: "email", Rule: "must contain @"})
}
if signup.Age < 18 {
problems = append(problems, FieldError{Field: "age", Rule: "must be at least 18"})
}
return errors.Join(problems...)
}
func main() {
err := validate(Signup{Email: "nope", Age: 15})
if err == nil {
panic("invalid signup should fail")
}
fmt.Println(err)
var fieldError FieldError
if !errors.As(err, &fieldError) {
panic("expected a FieldError in the joined error")
}
if fieldError.Field != "email" {
panic("expected the first field error to be reported")
}
combined, ok := err.(multiError)
if !ok || len(combined.Unwrap()) != 2 {
panic("expected two joined errors")
}
if validate(Signup{Email: "ada@example.com", Age: 30}) != nil {
panic("valid signup should pass")
}
}
How it works
Aggregate Field Errors with errors.Join keeps everything in the functions Error, validate and main.
Putting it to use
The primary signature is func (err FieldError) Error() string
There are 1 call inside main — validate — executed top to bottom.
The core lines of the flow
return errors.Join(problems...)
problems = append(problems, FieldError{Field: "age", Rule: "must be at least 18"})
problems = append(problems, FieldError{Field: "email", Rule: "must contain @"})
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- How do you run Aggregate Field Errors with errors.Join?
- Run it as a complete program — compile or interpret the file directly; there is nothing to install first.
Report a problem with this exampleOpens a pre-filled issue on GitHub.