-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.go
More file actions
406 lines (366 loc) · 12.6 KB
/
error.go
File metadata and controls
406 lines (366 loc) · 12.6 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
104
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
203
204
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
package restapi
// file deepcode ignore XSS: content written to http.ResponseWriter is safe
import (
"errors"
"fmt"
"maps"
"net/http"
"strings"
"time"
)
var (
// makeErrorResponse creates a response for an error by projecting the error
// and marshalling the result according to the acceptable content type for the
// request.
//
// See: func (*Error) makeResponse() for more details.
//
// This function is a variable to allow it to be replaced by tests.
makeErrorResponse = func(e *Error, rq *Request) *Response {
if e.statusCode != 0 && (e.statusCode < 400 || e.statusCode > 599) {
panic(fmt.Errorf("%w: %d: valid range for error status is 4xx-5xx", ErrInvalidStatusCode, e.statusCode))
}
// apply defaults in case the Error was not fully initialised
e.statusCode = coalesce(e.statusCode, http.StatusInternalServerError)
e.timeStamp = coalesce(e.timeStamp, nowUTC())
e.request = rq.Request
p := ProjectError(e.info())
statusCode := e.statusCode
contentType := rq.Accept
content, err := rq.MarshalContent(p)
if err != nil {
LogError(InternalError{
Err: err,
Message: "error marshalling error response",
Help: fmt.Sprintf("the original error was: %v", e),
Request: rq.Request,
})
return &Response{
StatusCode: http.StatusInternalServerError,
ContentType: "plain/text",
Content: []byte(strings.Join([]string{
"An error occurred marshalling an error response",
"",
"The marshalling error was:",
" " + err.Error(),
"",
"The original error was:",
" " + e.Error(),
}, "\n")),
}
}
// if returning the intended error response we do NOT include an ErrorInfo
// result since this signals an error in the error handling process
return &Response{
StatusCode: statusCode,
ContentType: contentType,
Content: content,
}
}
)
// Error holds details of a REST API error.
//
// The Error type is exported but has no exported members; an endpoint function
// will usually obtain an Error value using an appropriate factory function, using
// the exported methods to provide information about the error.
//
// # examples
//
// // an unexpected error occurred
// if err := SomeOperation(); err != nil {
// return restapi.InternalServerError(fmt.Errorf("SomeOperation: %w", err))
// }
//
// // an error occurred due to invalid input; provide guidance to the user
// if err := GetIDFromRequest(rq, &d); err != nil {
// return restapi.BadRequest().
// WithMessage("ID is missing or invalid").
// WithHelp("The ID must be a valid UUID provided in the request path: /v1/resource/<ID>")
//
// URL // the URL of the request that resulted in the error
// TimeStamp // the (UTC) time that the error occurred
//
// The following additional information may also be provided by a Handler when
// returning an Error:
//
// Message // a message to be displayed with the error. If not provided,
// // the message will be the string representation of the error (Err).
// //
// // NOTE: if Message is set, the Err string will NOT be used
//
// Help // a help message to be displayed with the error. If not provided,
// // the help message will be omitted from the response.
type Error struct {
err error
help *string
message *string
request *http.Request
statusCode int
timeStamp time.Time
properties map[string]any
headers
}
// NewError returns an Error with the specified status code. One or more additional
// arguments may be provided to be used as follows://
//
// int // the status code for the error
// error // an error to be wrapped by the Error
// string // a message to be displayed with (or instead of) an error
//
// If no status code is provided http.StatusInternalServerError will be used. If
// multiple int arguments are provided only the first will be used; any subsequent
// int arguments will be ignored.
//
// If multiple error arguments are provided they will be wrapped as a single error
// using errors.Join.
//
// If multiple string arguments are provided, the first non-empty string will be used
// as the message; any remaining strings will be ignored.
//
// The returned Error will have a timestamp set to the current time in UTC.
//
// # panics
//
// NewError will panic with the following errors:
//
// - ErrInvalidArgument if arguments of an unsupported type are provided.
// - ErrInvalidStatusCode if a status code is provided that is not in the range 4xx-5xx.
//
// # examples
//
// // no error occurred, but the operation was not successful
// return NewError(http.StatusNotFound, "no document exists with that ID")
//
// // an error occurred, but the error is not relevant to the user
// id, err := GetRequestID(rq)
// if err != nil {
// return NewError(http.BadRequest, "required document ID is missing or invalid", err)
// }
func NewError(args ...any) *Error {
var (
err error
msg *string
rq *http.Request
sc *int
)
errs := []error{}
strs := []string{}
for _, arg := range args {
switch v := arg.(type) {
case error:
errs = append(errs, v)
case int:
if v < 400 || v > 599 {
panic(fmt.Errorf("%w: %d: valid range for error status is 4xx-5xx", ErrInvalidStatusCode, v))
}
if sc == nil {
sc = &v
}
case string:
strs = append(strs, v)
case *http.Request:
rq = v
}
}
switch len(errs) {
case 0:
// NO-OP
case 1:
err = errs[0]
default:
err = errors.Join(errs...)
}
if len(strs) > 0 {
s := strings.Join(strs, " ")
msg = &s
}
return &Error{
statusCode: coalesce(ifNotNil(sc), http.StatusInternalServerError),
err: err,
message: msg,
request: rq,
timeStamp: nowUTC(),
}
}
// info returns an ErrorInfo representing the Error.
func (err *Error) info() ErrorInfo {
d := ErrorInfo{
StatusCode: err.statusCode,
Err: err.err,
Message: ifNotNil(err.message),
Help: ifNotNil(err.help),
Request: err.request,
TimeStamp: err.timeStamp,
}
if len(err.properties) > 0 {
d.Properties = make(map[string]any, len(err.properties))
for k, v := range err.properties {
d.Properties[k] = v
}
}
return d
}
// Error implements the error interface for an Error, returning a simplified string
// representation of the error in the form:
//
// <status code> <status>[: error][: message]
//
// where <status> is the http status text associated with <status code>; <error> and
// <message> are only included if they are set on the Error.
func (err Error) Error() string {
code := err.statusCode
status := http.StatusText(err.statusCode)
switch {
case err.err != nil && err.message != nil:
return fmt.Sprintf("%d %s: %s: %s", code, status, err.err, *err.message)
case err.err != nil:
return fmt.Sprintf("%d %s: %v", code, status, err.err)
case err.message != nil:
return fmt.Sprintf("%d %s: %s", code, status, *err.message)
default:
return fmt.Sprintf("%d %s", code, status)
}
}
// Is returns true if the target error is an Error and the Error matches the target
// error. An Error matches the target error if:
//
// - the status codes match or the target has no status code (matches any);
// - the messages match or the target has no message (matches any);
// - the help messages match or the target has no help message (matches any);
// - the properties match or the target has no properties (matches any);
// - the wrapped target error satisfies errors.Is() or the target has no wrapped
// error (matches any).
func (err Error) Is(target error) bool {
// allows target to be specified as either *Error or Error
var t *Error
switch target := target.(type) {
case *Error:
t = target
case Error:
t = &target
default:
return false
}
{
target := t
return (target.statusCode == 0 || err.statusCode == target.statusCode) &&
((target.message == nil) || (err.message == nil) || (*err.message == *target.message)) &&
((target.help == nil) || (err.help == nil) || (*err.help == *target.help)) &&
((target.properties == nil) || (err.properties == nil) || maps.Equal(err.properties, target.properties)) &&
((target.headers == nil) || (err.headers == nil) || maps.Equal(err.headers, target.headers)) &&
(target.err == nil || errors.Is(err.err, target.err))
}
}
// Unwrap returns the error wrapped by the Error (or nil).
func (apierr Error) Unwrap() error {
return apierr.err
}
// hasHeaders ensures that the Error headers member is an initialised map,
// making a new one if necessary.
func (err *Error) hasHeaders() headers {
if err.headers == nil {
err.headers = make(headers)
}
return err.headers
}
// hasProperties ensures that the Error properties member is an
// initialised map, making a new one if necessary.
func (err *Error) hasProperties() map[string]any {
if err.properties == nil {
err.properties = make(map[string]any)
}
return err.properties
}
// makeResponse ensures that the error has a valid status code, timestamp and
// request reference before creating a response by projecting the error
// and marshalling the result according to the acceptable content type for
// the request.
//
// If marshalling fails the response is formed by calling writeError with the
// marshalling error.
//
// An ErrorDetails object is also returned which provides the details of the
// error that was projected. This object will be passed to the LogError
// function to log the error.
//
// If marshalling the projected error fails, ErrorDetails will describe
// the original error, not the marshalling error.
func (apierr *Error) makeResponse(rq *Request) *Response {
return makeErrorResponse(apierr, rq)
}
// WithHeader sets a header to be included in the response for the error.
//
// The specified header will be added to any headers already set on the Error.
// If the specified header is already set on the Error the existing header will
// be replaced with the new value.
//
// The header key is canonicalised using http.CanonicalHeaderKey. To set a header
// with a non-canonical key use WithNonCanonicalHeader.
func (err *Error) WithHeader(k string, v any) *Error {
err.hasHeaders().set(k, v)
return err
}
// WithHeaders sets the headers to be included in the response for the error.
//
// The specified headers will be added to any headers already set on the Error.
// If the new headers contain values already set on the Error the existing headers
// will be replaced with the new values.
//
// The header keys are canonicalised using http.CanonicalHeaderKey. To set a header
// with a non-canonical key use WithNonCanonicalHeader.
func (err *Error) WithHeaders(headers map[string]any) *Error {
err.hasHeaders().setAll(headers)
return err
}
// WithHelp sets the help message for the error.
func (err *Error) WithHelp(s string) *Error {
err.help = &s
return err
}
// WithMessage sets the message for the error.
func (err *Error) WithMessage(s string) *Error {
err.message = &s
return err
}
// WithNonCanonicalHeader sets a non-canonical header to be included in the response
// for the error.
//
// The specified header will be added to any headers already set on the Error.
// If the specified header is already set on the Error the existing header will
// be replaced with the new value.
//
// The header key is not canonicalised; if the specified key is canonical then the
// canonical header will be set.
//
// WithNonCanonicalHeader should only be used when a non-canonical header key is
// specifically required (which is rare). Ordinarily WithHeader should be used.
func (err *Error) WithNonCanonicalHeader(k string, v any) *Error {
err.hasHeaders().setNonCanonical(k, v)
return err
}
// WithProperty sets a property for the error.
func (err *Error) WithProperty(key string, value any) *Error {
err.hasProperties()[key] = value
return err
}
// BadRequest returns an ApiError with a status code of 400 and the specified error.
func BadRequest(args ...any) *Error {
return NewError(append([]any{http.StatusBadRequest}, args...)...)
}
// Forbidden returns an ApiError with a status code of 403 and the specified error.
func Forbidden(args ...any) *Error {
return NewError(append([]any{http.StatusForbidden}, args...)...)
}
// InternalServerError returns an ApiError with a status code of 500 and the
// specified error.
func InternalServerError(args ...any) *Error {
return NewError(append([]any{http.StatusInternalServerError}, args...)...)
}
// NotFound returns an ApiError with a status code of 404 and the specified error.
func NotFound(args ...any) *Error {
return NewError(append([]any{http.StatusNotFound}, args...)...)
}
// Unauthorized returns an ApiError with a status code of 401 and the specified error.
func Unauthorized(args ...any) *Error {
return NewError(append([]any{http.StatusUnauthorized}, args...)...)
}