errors.Is used for checking error equalality

85 阅读1分钟

== is often used to check if two errors equal in golang, but in some cases, errors.Is is needed for checking if an error is wraped by another error, in which case == returns false, but errors.Is returns true.

Let's look at the below code,

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

func main() {

	err := someFunction()
	if err != ErrNotFound {
		fmt.Println("err != ErrNotFound")
	}

	if errors.Is(err, ErrNotFound) {
		fmt.Println("The error is 'not found'")
	} else {
		fmt.Println("The error is not 'not found':", err)
	}

	err = someFunction1()
	if errors.Is(err, ErrNotFound) {
		fmt.Println("err is ErrNotFound")
	}
}

func someFunction() error {
	return fmt.Errorf("this function failed: %w", ErrNotFound)
}

func someFunction1() error {
	return ErrNotFound
}

the output,

err != ErrNotFound
The error is 'not found'
err is ErrNotFound

ErrNotFound is the base error, someFunction returns an error which wraps ErrNotFound. The err!=ErrNotFound returns true, but errors.Is(err, ErrNotFound) returns true because err wraps ErrNotFound. So if you want to check if err is another error, errors.Is should be used.