-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
72 lines (62 loc) · 1.8 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
65
66
67
68
69
70
71
72
// Copyright (c) Mondoo, Inc.
// SPDX-License-Identifier: MPL-2.0
package ranger
import (
"io"
"net/http"
"github.com/rs/zerolog/log"
"go.mondoo.com/ranger-rpc/codes"
"go.mondoo.com/ranger-rpc/status"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
spb "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/protobuf/proto"
)
// HttpError writes an error to the response.
func HttpError(span trace.Span, 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())
span.RecordError(err, trace.WithAttributes(
attribute.Int("mondoo.ranger.status", status),
))
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 := io.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
}