-
Notifications
You must be signed in to change notification settings - Fork 120
/
error.go
93 lines (83 loc) · 2.33 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package option
import (
"context"
"errors"
"net/http"
"connectrpc.com/connect"
kubeerr "k8s.io/apimachinery/pkg/api/errors"
)
var (
_ connect.Interceptor = &errorInterceptor{}
)
type errorInterceptor struct{}
func newErrorInterceptor() connect.Interceptor {
return &errorInterceptor{}
}
func (i *errorInterceptor) WrapUnary(next connect.UnaryFunc) connect.UnaryFunc {
return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
res, err := next(ctx, req)
if err != nil {
return nil, i.toConnectError(err)
}
return res, nil
}
}
func (i *errorInterceptor) WrapStreamingClient(
next connect.StreamingClientFunc,
) connect.StreamingClientFunc {
// TODO: Support streaming client when necessary
return next
}
func (i *errorInterceptor) WrapStreamingHandler(
next connect.StreamingHandlerFunc,
) connect.StreamingHandlerFunc {
return func(ctx context.Context, conn connect.StreamingHandlerConn) error {
if err := next(ctx, conn); err != nil {
return i.toConnectError(err)
}
return nil
}
}
func (*errorInterceptor) toConnectError(err error) error {
var connectErr *connect.Error
if ok := errors.As(err, &connectErr); ok {
return err
}
var statusErr *kubeerr.StatusError
if ok := errors.As(err, &statusErr); ok {
return connect.NewError(httpStatusToConnectCode(statusErr.Status().Code), statusErr)
}
return connect.NewError(connect.CodeInternal, err)
}
func httpStatusToConnectCode(status int32) connect.Code {
switch status {
case http.StatusBadRequest:
return connect.CodeInvalidArgument
case http.StatusUnauthorized:
return connect.CodeUnauthenticated
case http.StatusForbidden:
return connect.CodePermissionDenied
case http.StatusNotFound:
return connect.CodeNotFound
case http.StatusConflict:
return connect.CodeAlreadyExists
case http.StatusGone:
return connect.CodeNotFound
case http.StatusUnprocessableEntity:
return connect.CodeInvalidArgument
case http.StatusTooManyRequests:
return connect.CodeResourceExhausted
case 499:
return connect.CodeCanceled
case http.StatusInternalServerError:
return connect.CodeInternal
case http.StatusNotImplemented:
return connect.CodeUnimplemented
case http.StatusServiceUnavailable:
return connect.CodeUnavailable
case http.StatusGatewayTimeout:
return connect.CodeDeadlineExceeded
default:
return connect.CodeInternal
}
}