-
Notifications
You must be signed in to change notification settings - Fork 402
/
errorhandling.go
49 lines (40 loc) · 1.03 KB
/
errorhandling.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
// Copyright (C) 2022 Storj Labs, Inc.
// See LICENSE for copying information.
package api
import (
"encoding/json"
"net/http"
"go.uber.org/zap"
)
// HTTPError holds http error entity with http status and error itself.
type HTTPError struct {
Status int
Err error
}
// Error returns http error's string representation.
func (e HTTPError) Error() string {
return e.Err.Error()
}
// ServeError writes JSON error to response output stream.
func ServeError(log *zap.Logger, w http.ResponseWriter, status int, err error) {
msg := err.Error()
fields := []zap.Field{
zap.Int("code", status),
zap.String("message", msg),
zap.Error(err),
}
if status == http.StatusNoContent {
return
} else if status/100 == 5 { // Check for 5XX status.
log.Error("returning error to client", fields...)
} else {
log.Debug("returning error to client", fields...)
}
w.WriteHeader(status)
err = json.NewEncoder(w).Encode(map[string]string{
"error": msg,
})
if err != nil {
log.Debug("failed to write json error response", zap.Error(err))
}
}