forked from infobloxopen/atlas-app-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 1
/
interceptor.go
46 lines (35 loc) · 1.08 KB
/
interceptor.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
package errors
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
)
// UnaryServerInterceptor returns grpc.UnaryServerInterceptor
// that should be used as a middleware to generate Error Messages
// with Details and Field Information with Mapping given.
func UnaryServerInterceptor(mapFuncs ...MapFunc) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (res interface{}, err error) {
// Initialize container with mapping.
container := InitContainer()
mapper := container.AddMapping(mapFuncs...)
// Save container in context.
ctx = NewContext(ctx, container)
// Execute handler.
res, err = handler(ctx, req)
if err != nil {
// Return container as-is.
if _, ok := err.(*Container); ok {
return nil, err
}
// Pass protobuf status.
if _, ok := status.FromError(err); ok {
return nil, err
}
// Perform mapping and return error if not nil.
if err := mapper.Map(ctx, err); err != nil {
return nil, err
}
}
return res, nil
}
}