-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.go
More file actions
72 lines (62 loc) · 1.98 KB
/
Copy pathbase.go
File metadata and controls
72 lines (62 loc) · 1.98 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
package xerror
import (
"github.com/gomooth/xerror/ecode"
"github.com/gomooth/xerror/xcode"
)
// CodeCarrier 错误码载体
type CodeCarrier interface {
ErrorCode() int
HttpStatus() int
XCode() xcode.XCode
}
// FieldCarrier 结构化字段载体
type FieldCarrier interface {
WithFields(fields ...Field) XError
// GetFields 返回字段切片的安全副本,可自由修改。
GetFields() []Field
}
// Messenger 消息载体接口
type Messenger interface {
// Message 返回当前层的错误消息(不含错误码前缀和下层信息)。
Message() string
// ChainMessage 返回从当前层向下拼接的完整消息链(不含错误码前缀)。
ChainMessage() string
}
type errorBase struct {
code xcode.XCode
fields []Field
stack *stack
chainMsg string
errStr string
}
// 以下 code 在所有构造路径中保证非 nil,可直接访问
func (b *errorBase) ErrorCode() int { return b.code.Code() }
func (b *errorBase) HttpStatus() int { return b.code.HttpStatus() }
func (b *errorBase) XCode() xcode.XCode { return b.code }
func (b *errorBase) ChainMessage() string { return b.chainMsg }
func (b *errorBase) Error() string { return b.errStr }
// IMPORTANT: Message() is NOT on errorBase. xError and xJoinedError have different semantics:
// - xError.Message() returns safeCode().String() (the current layer's message)
// - xJoinedError.Message() returns chainMsg (the first error's chain message)
func (b *errorBase) GetFields() []Field {
if b.fields == nil {
return nil
}
result := make([]Field, len(b.fields))
copy(result, b.fields)
return result
}
func (b *errorBase) ToMessage(config *ecode.Config) string {
fallback := b.code.String()
if len(fallback) == 0 {
fallback = b.Error()
}
if config == nil || config.Repository == nil {
return fallback
}
msg, err := ecode.FindMessage(config.Repository, b.code.Code(), config.Client, fallback)
if err != nil && config.OnError != nil {
config.OnError(err, b.code.Code())
}
return msg
}