Go

errors.Join — Aggregate Multiple Errors

admin by @admin ADMIN
Jun 13, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Go 1.20+ ships `errors.Join`, which combines multiple errors into one. Stop accumulating errors in a slice and stringifying yourself — use the standard library.
Go
Raw
package main

import (
    "errors"
    "fmt"
)

func validateUser(name, email string) error {
    var errs []error
    if name == "" {
        errs = append(errs, errors.New("name is required"))
    }
    if email == "" {
        errs = append(errs, errors.New("email is required"))
    }
    if len(name) > 50 {
        errs = append(errs, fmt.Errorf("name too long (%d)", len(name)))
    }
    return errors.Join(errs...)                         // nil if errs is empty
}

func main() {
    err := validateUser("", "")
    fmt.Println(err)
    // name is required
    // email is required

    // The joined error matches Is/As against any of its children
    if errors.Is(err, errors.New("name is required")) {
        fmt.Println("(would be true with sentinel errors)")
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.