-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
64 lines (56 loc) · 1.57 KB
/
error.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
package ranger
import (
"io"
"io/ioutil"
"net/http"
"github.com/rs/zerolog/log"
"go.mondoo.com/ranger-rpc/codes"
"go.mondoo.com/ranger-rpc/status"
spb "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/protobuf/proto"
)
// httpError writes an error to the response.
func httpError(w http.ResponseWriter, req *http.Request, err error) {
// check if the accept header is set, otherwise use the incoming content type
accept := determineResponseType(req.Header.Get("Content-Type"), req.Header.Get("Accept"))
// check that we got a status.Error package
s, ok := status.FromError(err)
if !ok {
s = status.New(codes.Unknown, err.Error())
}
h := w.Header()
// write status code
status := status.HTTPStatusFromCode(s.Code())
if status >= 500 {
log.Error().
Err(err).
Str("url", req.URL.Path).
Int("status", status).
Msg("returned internal error")
} else {
log.Debug().
Err(err).
Str("url", req.URL.Path).
Int("status", status).
Msg("non 5xx error")
}
// add body and content
// NOTE: we ignore the error here since its already an error that we return
payload, contentType, _ := convertProtoToPayload(s.Proto(), accept)
h.Set("Content-Type", contentType)
w.WriteHeader(status)
w.Write(payload)
}
// parseStatus tries to parse the proto Status from the body of the response.
func parseStatus(reader io.Reader) (*spb.Status, error) {
payload, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
var status spb.Status
err = proto.Unmarshal(payload, &status)
if err != nil {
return nil, err
}
return &status, nil
}