forked from thecodeteam/libstorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers_errors.go
58 lines (46 loc) · 1.17 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
package handlers
import (
"net/http"
"github.com/akutz/goof"
"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
}
ctx.Error(err)
httpErr := goof.NewHTTPError(err, getStatus(err))
httputils.WriteJSON(w, httpErr.Status(), httpErr)
return nil
}
func getStatus(err error) int {
switch err.(type) {
case *types.ErrBadAdminToken:
return http.StatusUnauthorized
case *types.ErrNotFound:
return http.StatusNotFound
default:
return http.StatusInternalServerError
}
}