Go core
Browse topics

errors.Join

Version
1.27
Since
1.20
Review
Draft

Summary#

errors.Join combines several errors into one. It drops nil arguments and returns nil when none remain. errors.Is and errors.As can inspect each joined error.

Syntax#

go
err = errors.Join(writeErr, closeErr)
err = errors.Join(problems...)

Example#

go
package main

import (
	"errors"
	"fmt"
)

var (
	errName = errors.New("name is required")
	errAge  = errors.New("age must be positive")
)

func validate(name string, age int) error {
	var problems []error
	if name == "" {
		problems = append(problems, errName)
	}
	if age <= 0 {
		problems = append(problems, errAge)
	}
	return errors.Join(problems...)
}

func main() {
	err := validate("", -1)
	fmt.Println(err)
	fmt.Println(errors.Is(err, errName), errors.Is(err, errAge))
	fmt.Println(errors.Unwrap(err) == nil)

	if list, ok := err.(interface{ Unwrap() []error }); ok {
		fmt.Println(len(list.Unwrap()))
	}
	fmt.Println(validate("Ada", 36) == nil)
}

Expected output#

Text
name is required
age must be positive
true true
true
2
true

Common mistakes#

errors.Unwrap returns nil for a joined error because the result implements Unwrap() []error. The combined message separates the original messages with newlines, which can split one log entry across lines in a plain-text log.

Version applicability#

Go 1.20 added errors.Join and made errors.Is and errors.As inspect errors that wrap several others. Earlier versions need a custom or third-party error list.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0