...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package baseapp
16
17 import (
18 "context"
19 "fmt"
20 "net/http"
21
22 "github.com/bluekeyes/hatpear"
23 "github.com/palantir/go-baseapp/pkg/errfmt"
24 "github.com/pkg/errors"
25 "github.com/rs/zerolog"
26 "github.com/rs/zerolog/hlog"
27 )
28
29
30
31 type httpError interface {
32 StatusCode() int
33 }
34
35
36
37 func RichErrorMarshalFunc(err error) interface{} {
38 switch err := err.(type) {
39 case hatpear.PanicError:
40 return fmt.Sprintf("%+v", err)
41 default:
42 return errfmt.Print(err)
43 }
44 }
45
46
47
48
49 func HandleRouteError(w http.ResponseWriter, r *http.Request, err error) {
50 var log *zerolog.Event
51
52
53
54 if cerr := r.Context().Err(); cerr == context.Canceled {
55 log = hlog.FromRequest(r).Debug()
56 WriteJSON(w, 499, map[string]string{
57 "error": "Client Closed Connection",
58 })
59 } else {
60 log = hlog.FromRequest(r).Error().Err(err)
61
62 cause := errors.Cause(err)
63 statusCode := http.StatusInternalServerError
64 if aerr, ok := cause.(httpError); ok {
65 statusCode = aerr.StatusCode()
66 }
67
68 rid, _ := hlog.IDFromRequest(r)
69 WriteJSON(w, statusCode, map[string]string{
70 "error": http.StatusText(statusCode),
71 "request_id": rid.String(),
72 })
73 }
74
75 log.Str("method", r.Method).
76 Str("path", r.URL.String()).
77 Msg("Unhandled error while serving route")
78 }
79
View as plain text