Recovery middleware is used for abnormal recovery and prevents the program from exiting directly in the event of an exception to the service.

configuration

Two configuration methods are available in recovery middleware WithHandler() and WithLogger()

WithHandler()

  1. func WithHandler(h HandlerFunc) Option {
  2. return func(o *options) {
  3. o.handler = h
  4. }
  5. }

When you set up a service exception, you can use a custom handler for handler processing, such as posting exception information to sentry.

WithLogger()

  1. func WithLogger(logger log.Logger) Option {
  2. return func(o *options) {
  3. o.logger = logger
  4. }
  5. }

To set up the logger for logging.

Usage

HTTP

  1. var opts = []http.ServerOption{
  2. http.Middleware(
  3. recovery.Recovery(
  4. recovery.WithLogger(log.DefaultLogger),
  5. recovery.WithHandler(func(ctx context.Context, req, err interface{}) error {
  6. // do someting
  7. return nil
  8. }),
  9. ),
  10. ),
  11. }
  12. srv := http.NewServer(opts...)

gRPC

  1. var opts = []grpc.ServerOption{
  2. grpc.Middleware(
  3. recovery.Recovery(
  4. recovery.WithLogger(log.DefaultLogger),
  5. recovery.WithHandler(func(ctx context.Context, req, err interface{}) error {
  6. // do someting
  7. return nil
  8. }),
  9. ),
  10. ),
  11. }
  12. srv := grpc.NewServer(opts...)