Library contents

Go errors.Is and fmt.Errorf

errors.Is checks an error and its wrapped causes for a match. The %w verb in fmt.Errorf preserves the underlying error for inspection.

A simple example

errors.Is and fmt.Errorf

  1. Start with An error wrapped with a note
  2. Do this Check for the original error
  3. Result Match
The wrapper retains the cause, so errors.Is can follow the chain.

Syntax

Go syntax
errors.Is(err, target)
Run this example in Go

Save the program as main.go. Use Go 1.21 or later.

go run main.go

Recognize a wrapped lookup error

A batch processor must distinguish an anticipated input problem from a different failure. Examine the operation's error information before deciding whether to skip one record, report the cause or stop.

First output linetrue
main.go
package main

import (
	"errors"
	"fmt"
)

func main() {
	missing := errors.New("missing item")
	err := fmt.Errorf("catalog lookup: %w", missing)
	fmt.Println(errors.Is(err, missing))
	fmt.Println(errors.Is(err, errors.New("missing item")))
}
Output
true
false

Two errors constructed separately can have identical text and different identities. Wrap a shared sentinel to preserve the meaning across application layers.

Go documentation for errors.Is and fmt.Errorf

Advertisements

Read a saved shift record

The closing clerk saved the file before leaving. Open the expected file and show the desk whether it is available.

Givenrecord.txt exists
Worked resultFile available

Handle an unsubmitted handover

The next shift opens an empty inbox before the first clerk submits a file. Open the expected file and show the desk whether it is available.

Givenrecord.txt missing
Worked resultAsk for the file