-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_handler.go
More file actions
187 lines (146 loc) · 4.27 KB
/
error_handler.go
File metadata and controls
187 lines (146 loc) · 4.27 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
package pages
import (
"embed"
"errors"
"log/slog"
"net/http"
"strings"
"github.com/gowool/keratin"
"github.com/gowool/keratin/middleware"
)
//go:embed error.gohtml
var ErrorTemplateFS embed.FS
type ErrorHandlerConfig struct {
// FallbackTemplate is a template name for fallback error page.
// The fallback template is used when the error page is not found
// by pattern, also the Site and Page variables could not be provided.
FallbackTemplate string
// StatusFunc returns an error code code.
StatusFunc middleware.ErrorStatusFunc
// JSONHandler is a handler for JSON error responses.
JSONHandler http.Handler
// Logger is used for logging.
Logger *slog.Logger
}
func (cfg *ErrorHandlerConfig) SetDefaults() {
if cfg.FallbackTemplate == "" {
cfg.FallbackTemplate = "error.gohtml"
}
if cfg.StatusFunc == nil {
cfg.StatusFunc = ErrorStatus
}
if cfg.JSONHandler == nil {
cfg.JSONHandler = http.HandlerFunc(cfg.jsonHandler)
}
if cfg.Logger == nil {
cfg.Logger = slog.Default()
}
cfg.Logger = cfg.Logger.WithGroup("http_error_handler")
}
func (cfg *ErrorHandlerConfig) jsonHandler(w http.ResponseWriter, r *http.Request) {
c := MustContext(r.Context())
data := map[string]any{
"code": c.Status(),
"message": http.StatusText(c.Status()),
}
if c.HasSite() {
data["site"] = map[string]any{
"id": c.Site().ID,
"name": c.Site().Name,
"url": c.Site().Home(),
}
}
if c.HasError() {
if httpErr, ok := errors.AsType[*keratin.HTTPError](c.Error()); ok && httpErr.Message != "" {
data["message"] = httpErr.Message
}
if c.Status() == http.StatusUnprocessableEntity {
data["data"] = c.Error()
} else if c.Debug() {
data["error"] = c.Error().Error()
}
}
if err := keratin.JSON(w, c.Status(), data); err != nil {
cfg.Logger.ErrorContext(r.Context(), "write response error", "error", err, "data", data)
}
}
type ErrorPatternFunc func(r *http.Request, status int, err error) string
func ErrorHandler(cfg ErrorHandlerConfig, pageHandler keratin.Handler, manager PageManager, errPattern ErrorPatternFunc) keratin.ErrorHandlerFunc {
if pageHandler == nil {
panic("http error handler: page handler is required")
}
if manager == nil {
panic("http error handler: page manager is required")
}
if errPattern == nil {
panic("http error handler: error pattern is required")
}
cfg.SetDefaults()
serveHTTP := func(w http.ResponseWriter, r *http.Request, logger *slog.Logger) {
if err := pageHandler.ServeHTTP(w, r); err != nil {
logger.Error("page handler error", "error", err)
}
}
return func(w http.ResponseWriter, r *http.Request, e error) {
logger := cfg.Logger
requestID := r.Header.Get(keratin.HeaderXRequestID)
if requestID == "" {
requestID = w.Header().Get(keratin.HeaderXRequestID)
}
if requestID != "" {
logger = logger.With("request_id", requestID)
}
ctx := r.Context()
if committed(w) {
logger.WarnContext(ctx, "response is committed, skip error handler", "error", e)
return
}
status := cfg.StatusFunc(ctx, e)
c := MustContext(ctx)
c.SetError(e)
c.SetPage(nil)
c.SetStatus(status)
c.SetTemplate(cfg.FallbackTemplate)
defer logger.ErrorContext(ctx, "request failed",
slog.Int("code", c.Status()),
slog.String("method", r.Method),
slog.Int("status_code", status),
slog.String("path", r.URL.Path),
slog.Bool("debug", c.Debug()),
slog.Bool("guest", c.Guest()),
slog.Any("error", e),
)
if r.Method == http.MethodHead {
w.WriteHeader(c.Status())
return
}
if strings.Contains(r.Header.Get(keratin.HeaderAccept), keratin.MIMEApplicationJSON) {
cfg.JSONHandler.ServeHTTP(w, r)
if committed(w) {
return
}
}
if !c.HasSite() {
logger.ErrorContext(ctx, "no site found in context", "error", e)
serveHTTP(w, r, logger)
return
}
pattern := errPattern(r, c.Status(), e)
if pattern == "" {
pattern = PageError5xx
}
page, err := manager.GetByPattern(ctx, c.Site(), pattern)
if err != nil {
logger.ErrorContext(ctx, "find page by pattern return error", "error", err, "pattern", pattern)
serveHTTP(w, r, logger)
return
}
c.SetTemplate("")
c.SetPage(page)
serveHTTP(w, r, logger)
}
}
func committed(w http.ResponseWriter) bool {
committer := keratin.ResponseCommitter(w)
return committer != nil && committer.Committed()
}