← 中文资源

简体中文版本

自定义 Is 方法做错误判等

错误类型实现 Is(error) bool 后,errors.Is 在解包链上会优先调用它:同一业务码的不同消息视为相等,错误匹配从指针比较升级成领域规则判等。

阅读英文原文

实现说明

自定义 Is 方法做错误判等可以归结为函数 Error、Is、main。

使用要点

  • 直接运行文件,输出会带上标签,比如 is not found:、is forbidden:、code mismatch:——输出的每一行都能指回产生它的那次调用。
  • main 按顺序串起 Is;运行文件就会把这个流程跑一遍。

常见问题

运行「自定义 Is 方法做错误判等」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 is not found:、is forbidden:、code mismatch: 标签标明各步骤。

入口签名:func (e *httpError) Error() string

核心语句

func (e *httpError) Error() string { return fmt.Sprintf("%d %s", e.code, e.msg) }
wrapped := fmt.Errorf("fetch user: %w", &httpError{code: 404, msg: "user 42 not found"})
other := fmt.Errorf("fetch order: %w", &httpError{code: 403, msg: "forbidden order"})

代码示例

package main

import (
	"errors"
	"fmt"
)

// 按错误码判等的领域错误:消息细节可以不同
type httpError struct {
	code int
	msg  string
}

func (e *httpError) Error() string { return fmt.Sprintf("%d %s", e.code, e.msg) }

// 自定义 Is:errors.Is 沿链解包时,遇到实现了 Is(error) bool 的错误会优先调用它
func (e *httpError) Is(target error) bool {
	var t *httpError
	if errors.As(target, &t) {
		return t.code == e.code
	}
	return false
}

var ErrNotFound = &httpError{code: 404, msg: "resource missing"}

func main() {
	wrapped := fmt.Errorf("fetch user: %w", &httpError{code: 404, msg: "user 42 not found"})
	// 消息与指针都不同,但业务码相同:Is 判等成立
	fmt.Println("is not found:", errors.Is(wrapped, ErrNotFound))

	other := fmt.Errorf("fetch order: %w", &httpError{code: 403, msg: "forbidden order"})
	fmt.Println("is forbidden:", errors.Is(other, &httpError{code: 403, msg: ""}))
	fmt.Println("code mismatch:", errors.Is(other, ErrNotFound))
}