-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy patherrors.go
More file actions
103 lines (85 loc) · 2.41 KB
/
Copy patherrors.go
File metadata and controls
103 lines (85 loc) · 2.41 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
package errors
import (
"encoding/json"
"errors"
"fmt"
)
const (
ErrTypeHTTP = "HTTP Error"
ErrTypeIO = "IO Error"
ErrTypeInvalidMethod = "Invalid Method"
ErrTypeAPI = "API Error"
ErrTypeJSON = "JSON Error"
ErrTypeAuth = "Auth Error"
ErrTypeTokenStore = "Token Store Error"
ErrTypeYAML = "YAML Error"
)
type Error struct {
Type string
Message string
cause error
}
func (e *Error) Error() string {
var js json.RawMessage
if json.Unmarshal([]byte(e.Message), &js) == nil {
return string(js)
}
if e.cause != nil {
return fmt.Sprintf("%s: %s (cause: %s)", e.Type, e.Message, e.cause)
}
return fmt.Sprintf("%s: %s", e.Type, e.Message)
}
func (e *Error) Unwrap() error {
return e.cause
}
func (e *Error) Is(target error) bool {
t, ok := target.(*Error)
if !ok {
return false
}
return e.Type == t.Type
}
func NewError(errorType, message string, cause error) *Error {
return &Error{
Type: errorType,
Message: message,
cause: cause,
}
}
func NewHTTPError(cause error) *Error {
return NewError(ErrTypeHTTP, cause.Error(), cause)
}
func NewIOError(cause error) *Error {
return NewError(ErrTypeIO, cause.Error(), cause)
}
func NewInvalidMethodError(method string) *Error {
return NewError(ErrTypeInvalidMethod, fmt.Sprintf("Invalid HTTP method: %s", method), nil)
}
func NewAPIError(data json.RawMessage) *Error {
return NewError(ErrTypeAPI, string(data), nil)
}
func NewJSONError(cause error) *Error {
return NewError(ErrTypeJSON, cause.Error(), cause)
}
func NewYAMLError(cause error) *Error {
return NewError(ErrTypeYAML, cause.Error(), cause)
}
func NewAuthError(message string, cause error) *Error {
return NewError(ErrTypeAuth, message, cause)
}
func NewTokenStoreError(message string) *Error {
return NewError(ErrTypeTokenStore, message, nil)
}
func IsErrorType(err error, errorType string) bool {
var e *Error
if ok := errors.As(err, &e); ok {
return e.Type == errorType
}
return false
}
func IsHTTPError(err error) bool { return IsErrorType(err, ErrTypeHTTP) }
func IsIOError(err error) bool { return IsErrorType(err, ErrTypeIO) }
func IsAPIError(err error) bool { return IsErrorType(err, ErrTypeAPI) }
func IsJSONError(err error) bool { return IsErrorType(err, ErrTypeJSON) }
func IsAuthError(err error) bool { return IsErrorType(err, ErrTypeAuth) }
func IsYAMLError(err error) bool { return IsErrorType(err, ErrTypeYAML) }