-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherr.go
More file actions
66 lines (54 loc) · 1.05 KB
/
err.go
File metadata and controls
66 lines (54 loc) · 1.05 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
package errwrap
import (
"errors"
"fmt"
"sync"
)
var (
defaultDomain = "service"
defaultDomainOnce sync.Once
)
func SetDomain(domain string) {
defaultDomainOnce.Do(func() {
defaultDomain = domain
})
}
// ErrorInfo is an error wrapper
type ErrorInfo struct {
Op string
Code ErrorCode
Domain string
Err error
Meta map[string]any
}
// Error returns error message
func (e *ErrorInfo) Error() string {
if e.Meta != nil {
return fmt.Sprintf("%s: [%s] %v | meta: %v", e.Op, e.Code, e.Err, e.Meta)
}
return fmt.Sprintf("%s: [%s] %v", e.Op, e.Code, e.Err)
}
// Unwrap returns the wrapped error
func (e *ErrorInfo) Unwrap() error {
return e.Err
}
// CodeOf returns error code
func CodeOf(err error) ErrorCode {
var appErr *ErrorInfo
if errors.As(err, &appErr) {
return appErr.Code
}
return CodeUnknown
}
// Wrap wraps an error into AppError
func Wrap(op string, code ErrorCode, err error, meta map[string]any) error {
if err == nil {
return nil
}
return &ErrorInfo{
Op: op,
Code: code,
Err: err,
Meta: meta,
}
}