forked from thecodeteam/libstorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers_errors.go
89 lines (75 loc) · 1.96 KB
/
handlers_errors.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
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
package handlers
import (
"encoding/json"
"net/http"
log "github.com/Sirupsen/logrus"
"github.com/akutz/goof"
"github.com/codedellemc/libstorage/api/context"
"github.com/codedellemc/libstorage/api/server/httputils"
"github.com/codedellemc/libstorage/api/types"
)
// errorHandler is a global HTTP filter for handlling errors
type errorHandler struct {
handler types.APIFunc
}
// NewErrorHandler returns a new global HTTP filter for handling errors.
func NewErrorHandler() types.Middleware {
return &errorHandler{}
}
func (h *errorHandler) Name() string {
return "error-handler"
}
func (h *errorHandler) Handler(m types.APIFunc) types.APIFunc {
return (&errorHandler{m}).Handle
}
// Handle is the type's Handler function.
func (h *errorHandler) Handle(
ctx types.Context,
w http.ResponseWriter,
req *http.Request,
store types.Store) error {
err := h.handler(ctx, w, req, store)
if err == nil {
return nil
}
gerr := goof.Newe(err)
ctx.WithError(gerr).Error("error: api call failed")
httpErr := goof.NewHTTPError(gerr, getStatus(err))
if isLogAPICallErrJSON(ctx) {
buf, err := json.Marshal(httpErr)
if err != nil {
ctx.WithError(err).Error(
"error marshalling api call err to json")
} else {
ctx.WithField("apiErr", string(buf)).Debug("api call error json")
}
}
httputils.WriteJSON(w, httpErr.Status(), httpErr)
return nil
}
func getStatus(err error) int {
if err == types.ErrMissingStorageService {
return http.StatusInternalServerError
}
switch err.(type) {
case *types.ErrBadAdminToken,
*types.ErrSecTokInvalid:
return http.StatusUnauthorized
case *types.ErrNotFound:
return http.StatusNotFound
case *types.ErrMissingInstanceID,
*types.ErrMissingLocalDevices:
return http.StatusBadRequest
default:
return http.StatusInternalServerError
}
}
func isLogAPICallErrJSON(ctx types.Context) bool {
if types.Debug {
return true
}
if lvl, ok := context.GetLogLevel(ctx); ok && lvl == log.DebugLevel {
return true
}
return false
}