Errors As Extracts The Target Type

Unwrap error chains with errors.As to reach a concrete error type, so code can read structured fields like Path or Timeout instead of parsing messages.

GoResilience

Code

gosnippet
32 lines
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
)

func loadConfig() error {
	// 底层是 *fs.PathError,外层用 %w 包装成业务错误
	_, err := os.ReadFile("missing.json")
	if err != nil {
		return fmt.Errorf("loading config: %w", err)
	}
	return nil
}

func main() {
	err := loadConfig()

	// errors.As 沿链查找第一个匹配的目标类型
	var pathErr *fs.PathError
	if errors.As(err, &pathErr) {
		fmt.Println("wrapped:", err)
		fmt.Println("op:", pathErr.Op, "path:", pathErr.Path)
	}

	// 接口目标同样成立:*fs.PathError 自带 Timeout() bool 方法,As 沿链填入接口变量
	var timeoutErr interface{ Timeout() bool }
	fmt.Println("has Timeout():", errors.As(err, &timeoutErr))
}

What the code does

Count the functions loadConfig and main as the entire surface area of Errors As Extracts The Target Type.

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.

Using it

Signature: func loadConfig() error

Running the file prints labeled results such as wrapped:, op:, has Timeout(): — each operation’s effect is visible in the output.

main calls 1 helper in sequence: loadConfig.

Key statements

return fmt.Errorf("loading config: %w", err)
if errors.As(err, &pathErr) {
	fmt.Println("wrapped:", err)
	fmt.Println("op:", pathErr.Op, "path:", pathErr.Path)
}

Interactive Tools for This Topic

FAQ

How are errors reported?
By return value: each fallible call hands back an `error`, checked at 1 place here.
What does Errors As Extracts The Target Type print when run?
No setup needed: run the file and look for labeled lines like `wrapped:`, `op:`, `has Timeout():` in the output.