status.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package status
  2. import (
  3. "context"
  4. "github.com/go-kratos/kratos/v2/errors"
  5. "github.com/go-kratos/kratos/v2/middleware"
  6. //lint:ignore SA1019 grpc
  7. )
  8. // HandlerFunc is middleware error handler.
  9. type HandlerFunc func(error) error
  10. // Option is recovery option.
  11. type Option func(*options)
  12. type options struct {
  13. handler HandlerFunc
  14. }
  15. // WithHandler with status handler.
  16. func WithHandler(h HandlerFunc) Option {
  17. return func(o *options) {
  18. o.handler = h
  19. }
  20. }
  21. // Server is an error middleware.
  22. func Server(opts ...Option) middleware.Middleware {
  23. options := options{
  24. handler: errorEncode,
  25. }
  26. for _, o := range opts {
  27. o(&options)
  28. }
  29. return func(handler middleware.Handler) middleware.Handler {
  30. return func(ctx context.Context, req interface{}) (interface{}, error) {
  31. reply, err := handler(ctx, req)
  32. if err != nil {
  33. return nil, options.handler(err)
  34. }
  35. return reply, nil
  36. }
  37. }
  38. }
  39. func errorEncode(err error) error {
  40. se := errors.FromError(err)
  41. if se == nil {
  42. se = errors.New(10400, "", "", err.Error())
  43. }
  44. return se.GRPCStatus().Err()
  45. }