What is errors.Is() Function in Golang

Golang errors.Is() function is “used to check 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

  1. err: 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.
  2. error: 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.

That’s it.