errors.Is Matches Sentinel Errors

Define package-level errors with errors.New, wrap them through layers, and match the sentinel with errors.Is even when the message has changed.

GoResilience

Code

snippet
package main

import (
	"errors"
	"fmt"
)

var ErrQuota = errors.New("quota exceeded")
var ErrAuth  = errors.New("unauthorized")

func charge(cents int) error {
	if cents > 5000 {
		return ErrQuota
	}
	return nil
}

func handlePayment(cents int) error {
	if err := charge(cents); err != nil {
		// %w 包装:消息带上下文,链上仍能匹配哨兵
		return fmt.Errorf("payment for %d cents: %w", cents, err)
	}
	return nil
}

func main() {
	err := handlePayment(9900)
	// 消息已变,但身份保留:Is 沿链逐层比较
	fmt.Println("is quota:", errors.Is(err, ErrQuota))
	fmt.Println("is auth:", errors.Is(err, ErrAuth))
	fmt.Println(err)
}

Peering into the code

errors.Is Matches Sentinel Errors comes down to the functions charge, handlePayment and main.

Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.
  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Using it

Signature: func charge(cents int) error

The demo output is labeled (is quota:, is auth:); each label names the call that printed it.

Running the file executes main, which drives handlePayment in order.

Key statements

return fmt.Errorf("payment for %d cents: %w", cents, err)
func charge(cents int) error {
	if cents > 5000 {
		return ErrQuota
	}
	return nil
}
func main() {
	err := handlePayment(9900)
	// 消息已变,但身份保留:Is 沿链逐层比较
	fmt.Println("is quota:", errors.Is(err, ErrQuota))
	fmt.Println("is auth:", errors.Is(err, ErrAuth))
	fmt.Println(err)
}

Interactive Tools for This Topic

FAQ

How does the code signal failure?
No exceptions — `error` returns checked at 1 site, and callers branch on `err` first.
What does errors.Is Matches Sentinel Errors print when run?
Run it as a complete program — the output lines carry labels such as `is quota:`, `is auth:`.