-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
162 lines (142 loc) · 4.64 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package gateway
import (
"context"
"fmt"
httpi "github.com/hopeio/cherry/utils/net/http"
"io"
"net/http"
"net/textproto"
"strings"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/hopeio/cherry/protobuf/errorcode"
"github.com/hopeio/cherry/utils/net/http/grpc/reconn"
stringsi "github.com/hopeio/cherry/utils/strings"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func CustomHTTPError(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, err error) {
s, ok := status.FromError(err)
if ok && s.Code() == 14 && strings.HasSuffix(s.Message(), `refused it."`) {
//提供一个思路,这里应该是哪条连接失败重连哪条,不能这么粗暴,map的key是个关键
if len(reconn.ReConnectMap) > 0 {
for _, f := range reconn.ReConnectMap {
f()
}
}
}
const fallback = `{"code": 14, "message": "failed to marshal error message"}`
w.Header().Del(httpi.HeaderTrailer)
contentType := marshaler.ContentType(nil)
w.Header().Set(httpi.HeaderContentType, contentType)
se, ok := err.(*errorcode.ErrRep)
if !ok {
se = &errorcode.ErrRep{Code: errorcode.Unknown, Message: err.Error()}
}
md, ok := runtime.ServerMetadataFromContext(ctx)
if !ok {
grpclog.Infof("Failed to extract ServerMetadata from context")
}
handleForwardResponseServerMetadata(w, md.HeaderMD)
buf, merr := marshaler.Marshal(se)
if merr != nil {
grpclog.Infof("Failed to marshal error message %q: %v", se, merr)
w.WriteHeader(http.StatusInternalServerError)
if _, err := io.WriteString(w, fallback); err != nil {
grpclog.Infof("Failed to write response: %v", err)
}
return
}
var wantsTrailers bool
if te := r.Header.Get(httpi.HeaderTE); strings.Contains(strings.ToLower(te), "trailers") {
wantsTrailers = true
handleForwardResponseTrailerHeader(w, md.TrailerMD)
w.Header().Set(httpi.HeaderTransferEncoding, "chunked")
}
/* st := HTTPStatusFromCode(se.Code)
w.WriteHeader(st)*/
if _, err := w.Write(buf); err != nil {
grpclog.Infof("Failed to write response: %v", err)
}
if wantsTrailers {
handleForwardResponseTrailer(w, md.TrailerMD)
}
}
func HTTPStatusFromCode(code errorcode.ErrCode) int {
switch code {
case errorcode.Success:
return http.StatusOK
case errorcode.Canceled:
return http.StatusRequestTimeout
case errorcode.Unknown:
return http.StatusInternalServerError
case errorcode.InvalidArgument:
return http.StatusBadRequest
case errorcode.DeadlineExceeded:
return http.StatusGatewayTimeout
case errorcode.NotFound:
return http.StatusNotFound
case errorcode.AlreadyExists:
return http.StatusConflict
case errorcode.PermissionDenied:
return http.StatusForbidden
case errorcode.Unauthenticated:
return http.StatusUnauthorized
case errorcode.ResourceExhausted:
return http.StatusTooManyRequests
case errorcode.FailedPrecondition:
// Note, this deliberately doesn't translate to the similarly named '412 Precondition Failed' HTTP response status.
return http.StatusBadRequest
case errorcode.Aborted:
return http.StatusConflict
case errorcode.OutOfRange:
return http.StatusBadRequest
case errorcode.Unimplemented:
return http.StatusNotImplemented
case errorcode.Internal:
return http.StatusInternalServerError
case errorcode.Unavailable:
return http.StatusServiceUnavailable
case errorcode.DataLoss:
return http.StatusInternalServerError
}
grpclog.Infof("Unknown gRPC error code: %v", code)
return http.StatusInternalServerError
}
func outgoingHeaderMatcher(key string) (string, bool) {
switch key {
case
httpi.HeaderSetCookie:
return key, true
}
return "", false
}
var headerMatcher = []string{httpi.HeaderSetCookie}
func handleForwardResponseServerMetadata(w http.ResponseWriter, md metadata.MD) {
for _, k := range headerMatcher {
if vs, ok := md[k]; ok {
for _, v := range vs {
w.Header().Add(k, v)
}
}
}
}
func handleForwardResponseTrailerHeader(w http.ResponseWriter, md metadata.MD) {
for k := range md {
tKey := textproto.CanonicalMIMEHeaderKey(fmt.Sprintf("%s%s", runtime.MetadataTrailerPrefix, k))
w.Header().Add("Trailer", tKey)
}
}
func handleForwardResponseTrailer(w http.ResponseWriter, md metadata.MD) {
for k, vs := range md {
tKey := fmt.Sprintf("%s%s", runtime.MetadataTrailerPrefix, k)
for _, v := range vs {
w.Header().Add(tKey, v)
}
}
}
func RoutingErrorHandler(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, w http.ResponseWriter, r *http.Request, httpStatus int) {
w.WriteHeader(httpStatus)
w.Header().Set("Content-Type", "text/xml; charset=utf-8")
w.Write(stringsi.ToBytes(http.StatusText(httpStatus)))
}