-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
88 lines (75 loc) · 2.34 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
87
88
package respond
import (
"errors"
"net/http"
)
var errorResponseUnknown = errorResponse{
Status: http.StatusInternalServerError,
Message: "unknown error",
}
// errorResponse contains both an error message and HTTP status code that provide
// enough information to respond with a meaningful error message and an appropriate
// 4XX/5XX status code to indicate the type of failure.
type errorResponse struct {
Status int `json:"status"`
Message string `json:"message,omitempty"`
}
// Status returns the HTTP status code you want to respond to the user with.
func (err errorResponse) StatusCode() int {
return err.Status
}
// Error contains the error message you want to send back to the caller.
func (err errorResponse) Error() string {
return err.Message
}
// ErrorWithStatus is a type of error that contains a Status() function which indicates
// the HTTP 4XX/5XX status code this type of failure should respond with.
type ErrorWithStatus interface {
error
Status() int
}
// ErrorWithStatusCode is a type of error that contains a StatusCode() function which indicates
// the HTTP 4XX/5XX status code this type of failure should respond with.
type ErrorWithStatusCode interface {
error
StatusCode() int
}
// ErrorWithCode is a type of error that contains a Code() function which indicates
// the HTTP 4XX/5XX status code this type of failure should respond with.
type ErrorWithCode interface {
error
Code() int
}
// toErrorWithStatus attempts to unwrap the given error, looking for Status(), StatusCode(), or
// Code() functions to extract a 4XX/5XX response, returning a strongly typed ErrorWithStatusCode that
// contains the HTTP status code and error message you can respond with.
func toErrorResponse(err error) errorResponse {
if err == nil {
return errorResponseUnknown
}
var errStatus ErrorWithStatus
if errors.As(err, &errStatus) {
return errorResponse{
Status: errStatus.Status(),
Message: errStatus.Error(),
}
}
var errStatusCode ErrorWithStatusCode
if errors.As(err, &errStatusCode) {
return errorResponse{
Status: errStatusCode.StatusCode(),
Message: errStatusCode.Error(),
}
}
var errCode ErrorWithCode
if errors.As(err, &errCode) {
return errorResponse{
Status: errCode.Code(),
Message: errCode.Error(),
}
}
return errorResponse{
Status: http.StatusInternalServerError,
Message: err.Error(),
}
}