-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunc_query.go
More file actions
99 lines (91 loc) · 2.55 KB
/
Copy pathfunc_query.go
File metadata and controls
99 lines (91 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package xerror
import (
"errors"
"github.com/gomooth/xerror/ecode"
"github.com/gomooth/xerror/xcode"
)
// Cause 返回错误链中下一个业务层错误(可能是 XError 或标准 error)。
// 对 XError:返回 Unwrap() 的结果(直接是业务层错误)。
// 对非 XError:等同 errors.Unwrap。
func Cause(err error) error {
if xe, ok := asXErrorInternal(err); ok {
return xe.Unwrap()
}
if unwrapper, ok := err.(interface{ Unwrap() error }); ok {
return unwrapper.Unwrap()
}
return nil
}
// RootCause 返回错误链的最底层 error。
// 对 XError:沿业务层链向下查找,返回最底层的业务错误。
// 对非 XError:沿 Unwrap 链查找最底层 error,支持多错误链(errors.Join 等)。
// 注意:多错误链(如 errors.Join)只递归第一个分支,其他分支的错误信息可能被遗漏。
func RootCause(err error) error {
if xe, ok := asXErrorInternal(err); ok {
for {
cause := xe.Unwrap()
if cause == nil {
return xe
}
next, ok := asXErrorInternal(cause)
if !ok {
return cause // 非 XError 的业务错误
}
xe = next
}
}
var root error
for cur := err; cur != nil; {
root = cur
unwrapper, ok := cur.(interface{ Unwrap() error })
if ok {
cur = unwrapper.Unwrap()
continue
}
if multi := unwrapMulti(cur); len(multi) > 0 {
return RootCause(multi[0])
}
break
}
return root
}
// AsXError 从错误链中提取最近的 XError。
func AsXError(err error) (XError, bool) {
var xe XError
return xe, errors.As(err, &xe)
}
// CollectCodes 递归收集错误链中所有错误码(去重)。
func CollectCodes(err error) []int {
if err == nil {
return nil
}
seen := make(map[int]bool)
var codes []int
collectCodesRecursive(err, seen, &codes, 0)
return codes
}
func collectCodesRecursive(err error, seen map[int]bool, codes *[]int, depth int) {
if depth > maxCollectDepth || err == nil {
return
}
// 收集当前层的错误码
if xe, ok := err.(XError); ok {
if code := xe.ErrorCode(); code != xcode.CodeNone && !seen[code] {
seen[code] = true
*codes = append(*codes, code)
}
}
// 统一遍历子错误
walkErrorChildren(err, func(child error) {
collectCodesRecursive(child, seen, codes, depth+1)
})
}
// ToClientMessage 将错误转为指定客户端的消息。
// 若 err 不是 XError,返回 err.Error()。
func ToClientMessage(err error, client ecode.Client, repo ecode.Repository) string {
xe, ok := asXErrorInternal(err)
if !ok {
return err.Error()
}
return xe.ToMessage(&ecode.Config{Client: client, Repository: repo})
}