-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
86 lines (72 loc) · 1.82 KB
/
errors.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
81
82
83
84
85
86
package tin
import (
"errors"
"fmt"
)
// Error contains the standard error definition for this domain.
type Error struct {
errorType string
cause error
message string
}
var (
// ErrNotSupported is used when the country is not supported
ErrNotSupported = NewError("Country not supported")
// ErrNetwork is an error that appears when there is a network issue
ErrNetwork = NewError("network")
// ErrInput is an error that appears when the input is invalid
ErrInput = NewError("input")
// ErrInvalid is an error that appears when the TIN number is invalid
ErrInvalid = NewError("invalid TIN")
)
func (e *Error) copy() *Error {
ne := new(Error)
*ne = *e
return ne
}
// NewError instantiates a new error.
func NewError(errorType string) *Error {
return &Error{errorType: errorType}
}
// WithCause attaches any error instance to the Error.
func (e *Error) WithCause(cause error) *Error {
ne := e.copy()
ne.cause = cause
return ne
}
// Error provides the string representation of the error.
func (e *Error) Error() string {
if e.message == "" {
if e.cause == nil {
return e.errorType
}
return e.cause.Error()
}
if e.cause == nil {
return e.message
}
return fmt.Sprintf("%s (%s)", e.message, e.cause.Error())
}
// WithMessage adds a message to the Error.
func (e *Error) WithMessage(message string) *Error {
ne := e.copy()
ne.message = message
return ne
}
// Is checks to see if the target error matches the current error or
// part of the chain.
func (e *Error) Is(target error) bool {
t, ok := target.(*Error)
if !ok {
return errors.Is(e.cause, target)
}
return e.errorType == t.errorType
}
// Cause returns the error that caused this error.
func (e *Error) Cause() error {
return e.cause
}
// Message returns just the message component, if present
func (e *Error) Message() string {
return e.message
}