-
Notifications
You must be signed in to change notification settings - Fork 0
/
apperror.go
60 lines (49 loc) · 1.42 KB
/
apperror.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
package main
import (
"net/http"
"go.uber.org/zap"
)
// HTTPError is an error that can be rendered into a HTML page to follow HTTP
// status semantics
type HTTPError struct {
Status int
Error error
}
func (app Datetime) error(httpErr HTTPError, w http.ResponseWriter, req *http.Request) {
tmpl := app.loadTemplate("error", w, req)
if tmpl == nil {
return
}
w.WriteHeader(httpErr.Status)
if req.Method == http.MethodHead {
return
}
err := tmpl.Execute(w, httpErr)
if err != nil {
l.Error("template failed", zap.Error(err))
app.templateError(HTTPError{http.StatusInternalServerError, err}, w, req)
return
}
}
func (app Datetime) simpleError(httpErr HTTPError, w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(httpErr.Status)
if req.Method == http.MethodHead {
return
}
if httpErr.Error != nil {
w.Write([]byte(http.StatusText(httpErr.Status) + ": " + httpErr.Error.Error()))
} else {
w.Write([]byte(http.StatusText(httpErr.Status)))
}
}
func (app Datetime) templateError(httpErr HTTPError, w http.ResponseWriter, req *http.Request) {
// Sadly, we probably already sent out the header
//w.Header().Set("Content-Type", "text/plain")
//w.WriteHeader(httpErr.Status)
if httpErr.Error != nil {
w.Write([]byte("\n" + http.StatusText(httpErr.Status) + ": " + httpErr.Error.Error()))
} else {
w.Write([]byte("\n" + http.StatusText(httpErr.Status)))
}
}