-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoded.go
80 lines (68 loc) · 1.76 KB
/
coded.go
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
package cerr
import (
"fmt"
)
// New returns a new CodedError.
func New() Error {
return new(CodedError)
}
// CodedError is a standard implemented of Error.
type CodedError struct {
// ErrCode contains an error code.
ErrCode string
// ErrInternal is an internal error.
ErrInternal error
// ErrShowInternalError defines whether or not to expose the internal error in any message output.
ErrShowInternalError bool
}
// Code returns the error code.
func (e *CodedError) Code() string {
return e.ErrCode
}
// Internal returns the errors internal message.
func (e *CodedError) Internal() error {
return e.ErrInternal
}
// WithCode sets the errors code.
func (e *CodedError) WithCode(code string) Error {
e.ErrCode = code
return e
}
// WithInternal sets the errors internal error.
func (e *CodedError) WithInternal(err error) Error {
e.ErrInternal = err
return e
}
// ShowInternal causes Error() to include the internal error.
func (e *CodedError) ShowInternal() Error {
e.ErrShowInternalError = true
return e
}
// HideInternal causes Error() to exclude the internal error.
func (e *CodedError) HideInternal() Error {
e.ErrShowInternalError = false
return e
}
// Error returns the error message.
func (e *CodedError) Error() string {
if e.ErrShowInternalError {
return fmt.Sprintf("%s: %s", e.ErrCode, e.ErrInternal)
} else {
return fmt.Sprintf("%s", e.ErrCode)
}
}
// Unwrap returns the internal error.
func (e *CodedError) Unwrap() error {
return e.ErrInternal
}
// Is returns true if the target error is a CodedError either no Code
// or the same Code as e.
func (e *CodedError) Is(target error) bool {
switch target := target.(type) {
case *CodedError:
targetCode := target.Code()
return targetCode == "" || targetCode == e.ErrCode
default:
return false
}
}