Custom Is Method For Error Matching

Errors can implement Is(error) bool so errors.Is matches by domain rules like status codes instead of requiring identical messages or pointers.

GoResilience

Code

gosnippet
35 lines
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))
}

How it works

Custom Is Method For Error Matching keeps everything in the functions Error, Is and main.

Putting it to use

The callable doing the work: func (e *httpError) Error() string

The demo output is labeled (is not found:, is forbidden:, code mismatch:), and each printed line traces back to the operation that emitted it.

The entry point wires Is together — run it once and the whole demo flows.

Core lines under the microscope

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"})

Interactive Tools for This Topic

FAQ

What does Custom Is Method For Error Matching print when run?
The script runs standalone; its 3 labeled outputs include `is not found:`, `is forbidden:`, `code mismatch:`.