-
Notifications
You must be signed in to change notification settings - Fork 10
/
error.go
108 lines (93 loc) · 2.17 KB
/
error.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package cmds
import (
"encoding/json"
"errors"
"fmt"
)
// ErrorType signfies a category of errors
type ErrorType uint
// ErrorTypes convey what category of error ocurred
const (
// ErrNormal is a normal error. The command failed for some reason that's not a bug.
ErrNormal ErrorType = iota
// ErrClient means the client made an invalid request.
ErrClient
// ErrImplementation means there's a bug in the implementation.
ErrImplementation
// ErrRateLimited is returned when the operation has been rate-limited.
ErrRateLimited
// ErrForbidden is returned when the client doesn't have permission to
// perform the requested operation.
ErrForbidden
// ErrorTimedOut is returned when the operation had timed out or was canceled.
ErrTimedOut
)
func (e ErrorType) Error() string {
return e.String()
}
func (e ErrorType) String() string {
switch e {
case ErrNormal:
return "command failed"
case ErrClient:
return "invalid argument"
case ErrImplementation:
return "internal error"
case ErrRateLimited:
return "rate limited"
case ErrForbidden:
return "request forbidden"
case ErrTimedOut:
return "timed out"
default:
return "unknown error code"
}
}
// Error is a struct for marshalling errors
type Error struct {
Message string
Code ErrorType
}
// Errorf returns an Error with the given code and format specification
func Errorf(code ErrorType, format string, args ...interface{}) Error {
return Error{
Code: code,
Message: fmt.Sprintf(format, args...),
}
}
func (e Error) Error() string {
return e.Message
}
// Unwrap returns the base error (an ErrorType). Works with go 1.13 error
// helpers.
func (e Error) Unwrap() error {
return e.Code
}
func (e Error) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Message string
Code ErrorType
Type string
}{
Message: e.Message,
Code: e.Code,
Type: "error",
})
}
func (e *Error) UnmarshalJSON(data []byte) error {
var w struct {
Message string
Code ErrorType
Type string
}
err := json.Unmarshal(data, &w)
if err != nil {
return err
}
if w.Type != "error" {
return errors.New("not of type error")
}
e.Message = w.Message
e.Code = w.Code
return nil
}