-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcustom_error_handler.go
56 lines (48 loc) · 1.41 KB
/
custom_error_handler.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
package errors
import (
"context"
"net/http"
"strconv"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/rs/zerolog"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/status"
)
const (
HTTPStatusErrorMetadata = "aserto-http-statuscode"
)
func CustomErrorHandler(
ctx context.Context,
gtw *runtime.ServeMux,
runtimeMarshaler runtime.Marshaler,
httpResponseWriter http.ResponseWriter,
httpRequest *http.Request,
err error,
) {
if err == nil {
runtime.DefaultHTTPErrorHandler(ctx, gtw, runtimeMarshaler, httpResponseWriter, httpRequest, err)
}
st := status.Convert(err)
for _, detail := range st.Details() {
errInfo, isErrInfo := detail.(*errdetails.ErrorInfo)
if !isErrInfo {
continue
}
value, hasErrorMetadata := errInfo.Metadata[HTTPStatusErrorMetadata]
if !hasErrorMetadata {
continue
}
code, conversionErr := strconv.Atoi(value)
if conversionErr != nil {
logger := zerolog.Ctx(ctx)
logger.Error().Err(conversionErr).Msg("Failed to detect http status code associated with this AsertoError")
} else {
var httpStatusError runtime.HTTPStatusError
httpStatusError.Err = err
httpStatusError.HTTPStatus = code
runtime.DefaultHTTPErrorHandler(ctx, gtw, runtimeMarshaler, httpResponseWriter, httpRequest, &httpStatusError)
return
}
}
runtime.DefaultHTTPErrorHandler(ctx, gtw, runtimeMarshaler, httpResponseWriter, httpRequest, err)
}