|
| 1 | +package grpcerrors |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/creasty/apperrors" |
| 5 | + "golang.org/x/net/context" |
| 6 | + "google.golang.org/grpc" |
| 7 | +) |
| 8 | + |
| 9 | +// StreamServerAppErrorHandlerFunc is a function that called by stream server interceptors when specified application erorrs are detected. |
| 10 | +type StreamServerAppErrorHandlerFunc func(context.Context, interface{}, interface{}, *grpc.StreamServerInfo, *apperrors.Error) error |
| 11 | + |
| 12 | +type streamServerAppErrorHandler struct { |
| 13 | + f StreamServerAppErrorHandlerFunc |
| 14 | +} |
| 15 | + |
| 16 | +func (h *streamServerAppErrorHandler) HandleStreamServerError(c context.Context, req interface{}, resp interface{}, info *grpc.StreamServerInfo, err error) error { |
| 17 | + appErr := apperrors.Unwrap(err) |
| 18 | + if appErr != nil { |
| 19 | + return h.f(c, req, resp, info, appErr) |
| 20 | + } |
| 21 | + return err |
| 22 | +} |
| 23 | + |
| 24 | +// WithStreamServerAppErrorHandler returns a new error handler for stream servers for handling errors wrapped with apperrors. |
| 25 | +func WithStreamServerAppErrorHandler(f StreamServerAppErrorHandlerFunc) StreamServerErrorHandler { |
| 26 | + return &streamServerAppErrorHandler{f: f} |
| 27 | +} |
| 28 | + |
| 29 | +// WithStreamServerReportableErrorHandler returns a new error handler for stream servers for handling errors annotated with the reportability. |
| 30 | +func WithStreamServerReportableErrorHandler(f StreamServerAppErrorHandlerFunc) StreamServerErrorHandler { |
| 31 | + return WithStreamServerAppErrorHandler(func(c context.Context, req interface{}, resp interface{}, info *grpc.StreamServerInfo, err *apperrors.Error) error { |
| 32 | + if err.Report { |
| 33 | + return f(c, req, resp, info, err) |
| 34 | + } |
| 35 | + return err |
| 36 | + }) |
| 37 | +} |
0 commit comments