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
|
package server
import (
"context"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var DefaultBuckPassing := NewCodeReplacer(codes.InvalidArgument, codes.Unknown, codes.Internal)
// NewCodeReplacer is an UnaryServerInterceptor replaces gRPC's status code.
//
// ## ref.
// * https://grpc.github.io/grpc/core/md_doc_statuscodes.html
func NewCodeReplacer(external codes.Code, internals codes.Code...) grpc.UnaryServerInterceptor {
targetCodes := map[codes.Code]struct{}{}
for _, c := range internals { targetCodes[c] = struct{}{} }
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
log := ctxzap.Extract(ctx)
m, err := handler(ctx, req)
if _, ok := targetCodes[status.Code(err)]; !ok {
return m, err
}
log.Info("TranslateTo")
return m, status.Error(external, err.Error())
}
}
|