-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
101 lines (86 loc) · 2.07 KB
/
Copy patherrors.go
File metadata and controls
101 lines (86 loc) · 2.07 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
package ohm
import (
"errors"
"net/http"
)
// HTTPError is an error with an HTTP response status.
type HTTPError struct {
Status int
Message string
Err error
}
// DecodeError is an error decoding malformed client request input.
type DecodeError struct {
Status int
Err error
}
// Error returns the error message.
func (e *HTTPError) Error() string {
if e.Message != "" {
return e.Message
}
if e.Err != nil {
return e.Err.Error()
}
return http.StatusText(e.responseStatus())
}
// Unwrap returns the underlying error.
func (e *HTTPError) Unwrap() error {
return e.Err
}
// Error returns the decode error message.
func (e *DecodeError) Error() string {
if e.Err != nil {
return e.Err.Error()
}
return http.StatusText(e.responseStatus())
}
// Unwrap returns the underlying decode error.
func (e *DecodeError) Unwrap() error {
return e.Err
}
// NewHTTPError creates an HTTPError.
func NewHTTPError(status int, message string, err error) *HTTPError {
return &HTTPError{
Status: status,
Message: message,
Err: err,
}
}
// DefaultErrorHandler renders handler errors as plain text.
func DefaultErrorHandler(req *Request, err error) {
status, message := ErrorResponse(err)
req.PlainText(status, message)
}
// ErrorResponse returns the safe HTTP status and public message for err.
func ErrorResponse(err error) (int, string) {
status := http.StatusInternalServerError
message := http.StatusText(status)
var httpErr *HTTPError
if errors.As(err, &httpErr) {
status = httpErr.responseStatus()
message = http.StatusText(status)
if httpErr.Message != "" {
message = httpErr.Message
}
return status, message
}
var decodeErr *DecodeError
if errors.As(err, &decodeErr) {
status = decodeErr.responseStatus()
message = http.StatusText(status)
}
return status, message
}
func (e *HTTPError) responseStatus() int {
if e.Status >= 100 && e.Status <= 999 {
return e.Status
}
return http.StatusInternalServerError
}
func (e *DecodeError) responseStatus() int {
if e.Status >= 400 && e.Status <= 499 {
return e.Status
}
return http.StatusBadRequest
}