Golang errors.Is() function is part of the standard “errors” package that checks if an error matches a specific target error. This function helps with error comparisons by determining if the given error is equal to, or wraps, the target error.
Syntax
func Is(err, target error) bool
Parameters
The tree consists of err itself, followed by the errors obtained by repeatedly calling Unwrap. When err wraps multiple errors, Is examines err followed by a depth-first traversal of its children.
An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.
Return value
It returns a boolean value, which is true if the err is equal to the target error or if the err wraps the target error. Otherwise, it returns false.
Example
package main
import (
"errors"
"fmt"
"io"
"os"
)
func main() {
_, err := os.Open("notavailable.txt")
if err != nil {
if errors.Is(err, os.ErrNotExist) {
fmt.Println("The file does not exist.")
} else if errors.Is(err, io.ErrUnexpectedEOF) {
fmt.Println("Unexpected EOF encountered.")
} else {
fmt.Println("An unknown error occurred:", err)
}
}
}
Output
The file does not exist.
In this example, we try to open a notavailable file, and an error is returned.
In the next step, we use the errors.Is() function to check if the error matches expected error cases, such as os.ErrNotExist or io.ErrUnexpectedEOF. If it does not match any of these cases, we print an “unknown error” message.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.