forked from nerva-framework/nerva
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
205 lines (190 loc) · 5.39 KB
/
Copy patherrors.go
File metadata and controls
205 lines (190 loc) · 5.39 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
package nerva
import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
)
// HTTPError is NERVA's controlled application error. Cause is retained for
// internal inspection and is never serialized by the default error handler.
type HTTPError struct {
Status int
Code string
Message string
Metadata Map
Cause error
}
// NewError creates a controlled HTTP error.
func NewError(status int, code, message string) *HTTPError {
return &HTTPError{Status: status, Code: code, Message: message}
}
// Error implements error.
func (e *HTTPError) Error() string {
if e == nil {
return "<nil>"
}
if e.Code == "" {
return e.Message
}
return e.Code + ": " + e.Message
}
// Unwrap exposes the internal cause to errors.Is and errors.As.
func (e *HTTPError) Unwrap() error {
if e == nil {
return nil
}
return e.Cause
}
// WithMetadata returns a shallow copy containing controlled response metadata.
func (e *HTTPError) WithMetadata(metadata Map) *HTTPError {
if e == nil {
return nil
}
clone := *e
if metadata != nil {
clone.Metadata = make(Map, len(metadata))
for key, value := range metadata {
clone.Metadata[key] = value
}
}
return &clone
}
// WithCause returns a shallow copy that wraps an internal error. The cause is
// not included in the HTTP response.
func (e *HTTPError) WithCause(cause error) *HTTPError {
if e == nil {
return nil
}
clone := *e
clone.Cause = cause
return &clone
}
// ErrorHandler converts handler errors into HTTP responses. It may be invoked
// concurrently for different requests and must protect shared state.
type ErrorHandler func(*Context, error)
type errorEnvelope struct {
Error errorBody `json:"error"`
}
type errorBody struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
Metadata Map `json:"metadata,omitempty"`
}
func defaultErrorHandler(c *Context, err error) {
if c.response.unavailable() {
slog.ErrorContext(
c.Request().Context(),
"nerva handler failed after response commit",
"request_id", sanitizeLogValue(c.RequestID(), 128),
"error_type", fmt.Sprintf("%T", err),
)
panic(http.ErrAbortHandler)
}
httpError := normalizeHTTPError(err)
var controlled *HTTPError
if !errors.As(err, &controlled) || controlled == nil || httpError.Status >= http.StatusInternalServerError {
slog.ErrorContext(
c.Request().Context(),
"nerva handler returned an error",
"request_id", sanitizeLogValue(c.RequestID(), 128),
"method", sanitizeLogValue(c.Method(), 32),
"path", sanitizeLogValue(c.Path(), 2048),
"status", httpError.Status,
"error_type", fmt.Sprintf("%T", err),
)
}
body := errorEnvelope{Error: errorBody{
Code: httpError.Code,
Message: httpError.Message,
RequestID: c.RequestID(),
Metadata: httpError.Metadata,
}}
payload, marshalErr := json.Marshal(body)
if marshalErr != nil {
slog.ErrorContext(
c.Request().Context(),
"nerva failed to serialize controlled error metadata",
"request_id", sanitizeLogValue(c.RequestID(), 128),
"method", sanitizeLogValue(c.Method(), 32),
"path", sanitizeLogValue(c.Path(), 2048),
"error_type", fmt.Sprintf("%T", marshalErr),
)
httpError = internalServerError()
body = errorEnvelope{Error: errorBody{
Code: httpError.Code,
Message: httpError.Message,
RequestID: c.RequestID(),
}}
payload, _ = json.Marshal(body)
}
payload = append(payload, '\n')
// Representation metadata set before an error does not describe this JSON
// response. In particular, a stale Content-Length can make net/http reject
// the body and a stale Content-Encoding can make clients misdecode it.
c.response.Header().Del("Content-Length")
c.response.Header().Del("Content-Encoding")
c.response.Header().Set("Content-Type", "application/json; charset=utf-8")
c.response.WriteHeader(httpError.Status)
if _, writeErr := c.response.Write(payload); writeErr != nil {
slog.ErrorContext(
c.Request().Context(),
"nerva failed to write centralized error response",
"request_id", sanitizeLogValue(c.RequestID(), 128),
"error_type", fmt.Sprintf("%T", writeErr),
)
panic(http.ErrAbortHandler)
}
}
func normalizeHTTPError(err error) *HTTPError {
if err == nil {
return internalServerError()
}
var httpError *HTTPError
if errors.As(err, &httpError) && httpError != nil {
clone := *httpError
if clone.Status < 400 || clone.Status > 599 {
return internalServerError()
}
if clone.Code == "" {
clone.Code = defaultErrorCode(clone.Status)
}
if clone.Message == "" {
clone.Message = http.StatusText(clone.Status)
if clone.Message == "" {
clone.Message = "HTTP error"
}
}
return &clone
}
return internalServerError().WithCause(fmt.Errorf("handler error: %w", err))
}
func defaultErrorCode(status int) string {
statusText := http.StatusText(status)
if statusText == "" {
return fmt.Sprintf("HTTP_%d", status)
}
var builder strings.Builder
underscore := false
for _, character := range strings.ToUpper(statusText) {
if (character >= 'A' && character <= 'Z') || (character >= '0' && character <= '9') {
builder.WriteRune(character)
underscore = false
continue
}
if !underscore && builder.Len() > 0 {
builder.WriteByte('_')
underscore = true
}
}
return strings.TrimSuffix(builder.String(), "_")
}
func internalServerError() *HTTPError {
return NewError(
http.StatusInternalServerError,
"INTERNAL_SERVER_ERROR",
"Internal server error",
)
}