Newer
Older
// Package errors defines structured errors which can
// be used for nesting errors with propagation
// of error identifiers and their messages.
// It also supports JSON serialization, so service to
// service communication can preserve error Kind.
package errors
import (
"bytes"
"encoding/json"
"net/http"
)
var separator = ": "
type Kind int
const (
Unknown Kind = iota // Unknown error.
BadRequest // BadRequest specifies invalid arguments or operation.
Unauthorized // Unauthorized request.
Forbidden // Forbidden operation.
Exist // Exist already.
NotFound // NotFound specifies that a resource does not exist.
Timeout // Timeout of request.
Internal // Internal error or inconsistency.
ServiceUnavailable
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
)
type Error struct {
// ID is a unique error identifier.
ID string
// Kind of error returned to the caller.
Kind Kind
// Message is a description of the error.
Message string
// The underlying error that triggered this one, if any.
Err error
}
func (k Kind) String() string {
switch k {
case Unknown:
return "unknown error"
case BadRequest:
return "bad request"
case Unauthorized:
return "not authenticated"
case Forbidden:
return "permission denied"
case Exist:
return "already exist"
case NotFound:
return "not found"
case Timeout:
return "timeout"
case Internal:
return "internal error"
case ServiceUnavailable:
return "service unavailable"
}
return "unknown error kind"
}
// New builds an error value from its arguments.
// There must be at least one argument or New panics.
// The type of each argument determines its meaning.
// If more than one argument of a given type is presented, only the last one is
// recorded.
//
// The supported types are:
//
// errors.Kind:
// The kind of the error.
// *errors.Error
// The underlying error that triggered this one. If the error has
// non-empty ID and Kind fields, they are promoted as values of the
// returned one.
// error:
// The underlying error that triggered this one.
// string:
// Treated as an error message and assigned to the Message field.
func New(args ...interface{}) error {
if len(args) == 0 {
panic("call to errors.New without arguments")
}
e := &Error{}
var innerKind = Unknown
for _, arg := range args {
switch arg := arg.(type) {
case Kind:
e.Kind = arg
case *Error:
errCopy := *arg
e.Err = &errCopy
e.ID = errCopy.ID
innerKind = errCopy.Kind
e.Message = errCopy.Message
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
}
case error:
e.Err = arg
case string:
e.Message = arg
}
}
if e.ID == "" {
e.ID = NewID()
}
if e.Kind == Unknown {
e.Kind = innerKind
}
return e
}
// Is reports whether err is an *Error of the given Kind.
func Is(kind Kind, err error) bool {
cerr, ok := err.(*Error)
return ok && cerr.Kind == kind
}
// Error returns description of the error.
func (e *Error) Error() string {
if e == nil {
return "nil"
}
if e.ID == "" {
e.ID = NewID()
}
b := new(bytes.Buffer)
b.WriteString(e.Message)
if e.Kind != 0 {
pad(b, separator)
b.WriteString(e.Kind.String())
}
if e.Err != nil {
pad(b, separator)
if cerr, ok := e.Err.(*Error); ok {
b.WriteString(cerr.errorSkipID())
} else {
b.WriteString(e.Err.Error())
}
}
b.WriteRune(' ')
b.WriteRune('(')
b.WriteString(e.ID)
b.WriteRune(')')
return b.String()
}
func (e *Error) errorSkipID() string {
if e == nil {
return "nil"
}
b := new(bytes.Buffer)
b.WriteString(e.Message)
if e.Kind != 0 {
pad(b, separator)
b.WriteString(e.Kind.String())
}
if e.Err != nil {
pad(b, separator)
if cerr, ok := e.Err.(*Error); ok {
b.WriteString(cerr.errorSkipID())
} else {
b.WriteString(e.Err.Error())
}
}
return b.String()
}
// StatusCode returns the HTTP status code corresponding to the error.
func (e *Error) StatusCode() int {
switch e.Kind {
case BadRequest:
return http.StatusBadRequest
case Unauthorized:
return http.StatusUnauthorized
case Forbidden:
return http.StatusForbidden
case Exist:
return http.StatusConflict
case NotFound:
return http.StatusNotFound
case Timeout:
return http.StatusRequestTimeout
case Internal:
return http.StatusInternalServerError
case ServiceUnavailable:
return http.StatusServiceUnavailable
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
default:
return http.StatusInternalServerError
}
}
// MarshalJSON returns the JSON representation of an Error.
func (e *Error) MarshalJSON() (data []byte, err error) {
var d = struct {
ID string `json:"id,omitempty"`
Kind Kind `json:"kind"`
Message string `json:"message,omitempty"`
}{
ID: e.ID,
Kind: e.Kind,
Message: e.Message,
}
return json.Marshal(d)
}
// UnmarshalJSON decodes a JSON encoded Error.
func (e *Error) UnmarshalJSON(data []byte) error {
var d struct {
ID string `json:"id,omitempty"`
Kind Kind `json:"kind"`
Message string `json:"message,omitempty"`
}
if err := json.Unmarshal(data, &d); err != nil {
return err
}
*e = Error{
ID: d.ID,
Kind: d.Kind,
Message: d.Message,
}
return nil
}
func JSON(w http.ResponseWriter, err error, statusCode ...int) {
var e error
var ok bool
if e, ok = err.(*Error); !ok {
e = New(err)
}
// check if the error can report its own status code
code := http.StatusInternalServerError
if sc, ok := e.(interface {
StatusCode() int
}); ok {
code = sc.StatusCode()
}
// overwrite the status code if it's explicitly passed as argument
if len(statusCode) > 0 {
code = statusCode[0]
}
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(e)
}
// Temporary reports if an Error is temporary and
// whether the request can be retried.
func (e *Error) Temporary() bool {
return e != nil && (e.Kind == Internal || e.Kind == Timeout)
}
// GetKind returns error kind determined
// by the specified HTTP status code.
func GetKind(statusCode int) Kind {
switch statusCode {
case http.StatusBadRequest:
return BadRequest
case http.StatusUnauthorized:
return Unauthorized
case http.StatusForbidden:
return Forbidden
case http.StatusConflict:
return Exist
case http.StatusNotFound:
return NotFound
case http.StatusRequestTimeout:
return Timeout
case http.StatusInternalServerError:
return Internal
case http.StatusServiceUnavailable:
return ServiceUnavailable