Go 1.27 reference · Errors, Context and Time

Go errors.Is and errors.As Function

Check whether an error chain contains a specific error value (Is) or an error of a specific type (As).

Go 1.27

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func Is(err, target error) bool   func As(err error, target any) bool

Parameters

ParameterDescription
Is(err, ErrX) Sentinel error comparison through wrapping.
As(err, &target) Extract a typed error from the chain.
errors.Join Combine several errors.

Examples

Example 1
package main

import (
	"errors"
	"fmt"
)

var ErrNotFound = errors.New("not found")

func main() {
	err := fmt.Errorf("get user 7: %w", ErrNotFound)
	fmt.Println(err == ErrNotFound, errors.Is(err, ErrNotFound))
}

Output

false true

Run this on your computer — see “Get Started” for setup.

errors.As and errors.Join
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
)

func main() {
	_, err := os.Open("missing.txt")
	var pathErr *fs.PathError
	if errors.As(err, &pathErr) {
		fmt.Println("op:", pathErr.Op, "path:", pathErr.Path)
	}
	joined := errors.Join(errors.New("a failed"), errors.New("b failed"))
	fmt.Println(joined)
}

Output

op: open path: missing.txt
a failed
b failed

Run this on your computer — see “Get Started” for setup.

Was this page helpful?