-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
120 lines (100 loc) · 2.18 KB
/
errors.go
File metadata and controls
120 lines (100 loc) · 2.18 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package errors
import (
"fmt"
"time"
)
// Error 定义Error的通用接口
type Error interface {
error
Code() string
Message() string
HttpStatus() int
Type() ErrType
Timestamp() time.Time
StackTrace() string
Metadata() map[string]any
WithMetadata(key string, val any) Error
WithMetadataMap(metadata map[string]any) Error
Unwrap() error
}
type ErrType string
const (
ErrTypeInternal ErrType = "INTERNAL"
ErrTypeBadRequest ErrType = "BAD_REQUEST"
ErrTypeUnauthorized ErrType = "UNAUTHORIZED"
ErrTypeForbidden ErrType = "FORBIDDEN"
ErrTypeNotFound ErrType = "NOT_FOUND"
ErrTypeConflict ErrType = "CONFLICT"
ErrTypeValidation ErrType = "VALIDATION"
ErrTypeBusiness ErrType = "BUSINESS"
ErrTypeTimeout ErrType = "TIMEOUT"
ErrTypeRateLimit ErrType = "RATE_LIMIT"
ErrTypeExternal ErrType = "EXTERNAL"
)
func (e ErrType) String() string {
return string(e)
}
type ErrorImpl struct {
// 错误码
code string
// 详细信息
message string
// http状态码
httpStatus int
// 错误类型
errType ErrType
// 时间戳
timestamp time.Time
// 堆栈信息
stackTrace string
// 原始的错误,error类型
cause error
// 其它的元数据
metadata map[string]any
}
func (e *ErrorImpl) Error() string {
if e.cause != nil {
return fmt.Sprintf("%s:%s", e.message, e.cause.Error())
}
return e.message
}
func (e *ErrorImpl) Code() string {
return e.code
}
func (e *ErrorImpl) Message() string {
return e.message
}
func (e *ErrorImpl) HttpStatus() int {
return e.httpStatus
}
func (e *ErrorImpl) Type() ErrType {
return e.errType
}
func (e *ErrorImpl) Timestamp() time.Time {
return e.timestamp
}
func (e *ErrorImpl) StackTrace() string {
return e.stackTrace
}
func (e *ErrorImpl) Unwrap() error {
return e.cause
}
func (e *ErrorImpl) WithMetadata(key string, val any) Error {
if e.metadata == nil {
e.metadata = make(map[string]any)
}
e.metadata[key] = val
return e
}
func (e *ErrorImpl) WithMetadataMap(metadata map[string]any) Error {
if e.metadata == nil {
e.metadata = make(map[string]any)
}
for k, v := range metadata {
e.metadata[k] = v
}
return e
}
func (e *ErrorImpl) Metadata() map[string]any {
return e.metadata
}