Error Wrapping With Is And As

Wrap errors with %w and inspect chains with errors.Is and errors.As so sentinel checks survive across package boundaries.

GoResilience

Code

gosnippet
41 lines
package main

import (
	"errors"
	"fmt"
	"os"
)

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

type ValidationError struct {
	Field string
}

func (e *ValidationError) Error() string {
	return fmt.Sprintf("invalid field %q", e.Field)
}

func loadConfig(path string) error {
	if _, err := os.Open(path); err != nil {
		// %w 包装:链路保留,errors.Is/As 仍可穿透
		return fmt.Errorf("load config %q: %w", path, ErrNotFound)
	}
	return nil
}

func validate(name string) error {
	return &ValidationError{Field: name}
}

func main() {
	err := errors.Join(loadConfig("missing.toml"), validate("port"))
	fmt.Println(err)

	// Is:沿链匹配哨兵值
	fmt.Println("is ErrNotFound:", errors.Is(err, ErrNotFound))

	// As:沿链提取具体类型
	var ve *ValidationError
	fmt.Println("as ValidationError:", errors.As(err, &ve), "field:", ve.Field)
}

How the snippet works

Count the functions Error, loadConfig, validate and main as the entire surface area of Error Wrapping With Is And As.

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

What to watch for

  • Handle err before the other return values; that ordering is the whole contract.

Applying it

Entry signature: func (e *ValidationError) Error() string

The demo output is labeled (is ErrNotFound:, as ValidationError:), letting each printed line point back to the operation that emitted it.

main calls 2 helpers in sequence: loadConfig and validate.

Statements that matter most here

return fmt.Errorf("load config %q: %w", path, ErrNotFound)
return fmt.Sprintf("invalid field %q", e.Field)
return &ValidationError{Field: name}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
The Go way: `err` comes back from each call, and 1 checkpoint here test it before proceeding.
What does Error Wrapping With Is And As print when run?
Execute the whole file; each printed line is prefixed with a label like `is ErrNotFound:`, `as ValidationError:`.