← 中文资源

简体中文版本

自定义错误解包底层原因

自定义错误实现 Unwrap 方法把原因挂入错误链:errors.Unwrap 逐层解包,errors.Is 穿透匹配哨兵错误;没有 Unwrap 方法的层返回 nil 终止。

阅读英文原文

运行说明

QueryError 同时携带操作名与 Cause,它的 Unwrap 方法把原因交给 errors 包。示例先打印组合后的消息,再连续调用 errors.Unwrap:第一次露出底层哨兵错误,第二次演示链条到 nil 终止。

errors.Is 沿这条链逐层匹配 errStoreDown,打印出的 true 说明自定义错误可以与只认识哨兵的代码互通。

要点提示

  • 没有 Unwrap 方法时,errors.Unwrap 返回 nil,errors.Is 也无法继续匹配。
  • Error() 把 Op 与原因文本拼接,消息可读的同时解包链保持结构化。

核心语句

func (e *QueryError) Unwrap() error { return e.Cause }

代码示例

package main

import (
	"errors"
	"fmt"
)

var errStoreDown = errors.New("store unavailable")

type QueryError struct {
	Op    string
	Cause error
}

// custom errors expose their cause through Unwrap
func (e *QueryError) Unwrap() error { return e.Cause }

func (e *QueryError) Error() string {
	return e.Op + ": " + e.Cause.Error()
}

func main() {
	err := &QueryError{Op: "load", Cause: errStoreDown}

	fmt.Println("printed:", err.Error())

	// peel one layer manually
	fmt.Println("unwrap once:", errors.Unwrap(err))

	// QueryError wraps one layer, so the second unwrap hits nil
	fmt.Println("unwrap twice:", errors.Unwrap(errors.Unwrap(err)))

	// errors.Is walks the Unwrap chain to reach the sentinel
	fmt.Println("is store down?", errors.Is(err, errStoreDown))
}