wx

关注公众号

errors


Golang 标准库 - errors

errors 包实现了操作错误的函数。Go 语言使用 error 值来表示错误状态,error 类型是内置的接口类型。

主要功能说明:

  1. 创建错误

    • New() 创建简单错误
    • Errorf() 格式化创建错误
  2. 错误包装

    • Wrap() 包装错误(需 fmt 包)
    • %w 动词包装错误
    • Unwrap() 解包错误
  3. 错误判断

    • Is() 判断错误是否匹配
    • As() 类型断言错误
  4. 自定义错误类型

    • 实现 error 接口
    • 添加额外信息

// 自定义错误类型
type NotFoundError struct {
	Resource string
	ID       string
}

func (e *NotFoundError) Error() string {
	return fmt.Sprintf("%s with id %s not found", e.Resource, e.ID)
}

func main() {
	// 1. 创建错误
	fmt.Println("=== 创建错误 ===")
	err1 := errors.New("something went wrong")
	fmt.Println("简单错误:", err1)

	err2 := fmt.Errorf("user %d not found", 123)
	fmt.Println("格式化错误:", err2)

	// 2. 错误包装
	fmt.Println("\n=== 错误包装 ===")
	originalErr := errors.New("database connection failed")
	wrappedErr := fmt.Errorf("failed to fetch user: %w", originalErr)
	fmt.Println("包装错误:", wrappedErr)

	// 解包错误
	unwrappedErr := errors.Unwrap(wrappedErr)
	fmt.Println("解包错误:", unwrappedErr)

	// 3. 错误判断
	fmt.Println("\n=== 错误判断 ===")
	var targetErr = errors.New("not found")
	
	newErr := fmt.Errorf("wrapped: %w", targetErr)
	
	// 使用 Is 判断
	if errors.Is(newErr, targetErr) {
		fmt.Println("错误匹配!")
	}

	// 使用 As 进行类型断言
	var notFound *NotFoundError
	testErr := &NotFoundError{Resource: "user", ID: "123"}
	if errors.As(testErr, &notFound) {
		fmt.Printf("捕获到 NotFoundError: Resource=%s, ID=%s\n", 
			notFound.Resource, notFound.ID)
	}

	// 4. 错误链
	fmt.Println("\n=== 错误链 ===")
	err := doSomething()
	if err != nil {
		fmt.Println("错误链:", err)
	}
}

func doSomething() error {
	return fmt.Errorf("doSomething failed: %w", 
		fmt.Errorf("inner operation: %w", 
			errors.New("root cause")))
}
如有疑问关注公众号给我留言
wx

关注公众号

©2017-2023 鲁ICP备17023316号-1 Powered by Hugo