Debian Codegraph @

errcheck.go

raw symbols SCIP
1 package check
2
3 import (
4 "sync"
5 )
6
7 //nolint:gochecknoglobals // Registry of custom error checkers.
8 var (
9 errCheckersMu sync.RWMutex
10 errCheckers []ErrChecker
11 )
12
13 // ErrChecker compares actual and expected errors.
14 // ok=false means "this checker does not apply to this pair"
15 // and the next registered checker (then the built-in logic) is consulted.
16 type ErrChecker func(actual, expected error) (equal, ok bool)
17
18 // ResetErrCheckers removes all registered error checkers,
19 // including the built-in CheckFieldError.
20 //
21 // Combine with RegisterErrChecker to define a custom chain in a specific order.
22 //
23 // Intended for TestMain.
24 // Not safe to call concurrently with running checks.
25 func ResetErrCheckers() {
26 errCheckersMu.Lock()
27 defer errCheckersMu.Unlock()
28 errCheckers = nil
29 }
30
31 // RegisterErrChecker adds a custom error comparison strategy used by Err and NotErr.
32 // Checkers run in registration order before built-in logic.
33 //
34 // Intended to be called from init() or TestMain.
35 // Not safe to call concurrently with running checks.
36 func RegisterErrChecker(f ErrChecker) {
37 errCheckersMu.Lock()
38 defer errCheckersMu.Unlock()
39 errCheckers = append(errCheckers, f)
40 }
41
42 // runCheckers iterates registered checkers with the original actual/expected errors.
43 // Returns (equal, ok) where ok=true means a checker claimed this pair.
44 func runCheckers(actual, expected error) (equal, ok bool) {
45 errCheckersMu.RLock()
46 defer errCheckersMu.RUnlock()
47 for _, check := range errCheckers {
48 if eq, claimed := check(actual, expected); claimed {
49 return eq, true
50 }
51 }
52 return false, false
53 }