默认情况下,一个恐慌将转换成一个gRPC错误’ code.Internal ‘
处理可以通过提供替代恢复功能进行定制。
func StreamServerInterceptor(opts …Option) grpc.StreamServerInterceptor
func UnaryServerInterceptor(opts …Option) grpc.UnaryServerInterceptor

type Option

func WithRecoveryHandler(f RecoveryHandlerFunc) Option

type RecoveryHandlerFunc

type RecoveryHandlerFunc func(p interface{}) (err error)

例子:

  1. var (
  2. customFunc grpc_recovery.RecoveryHandlerFunc
  3. )
  4. // Initialization shows an initialization sequence with a custom recovery handler func.
  5. func main() {
  6. //定义customfunc来处理恐慌
  7. customFunc = func(p interface{}) (err error) {
  8. return status.Errorf(codes.Unknown, "panic triggered: %v", p)
  9. }
  10. opts := []grpc_recovery.Option{
  11. grpc_recovery.WithRecoveryHandler(customFunc),
  12. }
  13. // 创建一个服务器。恢复处理程序通常位于链的最后,以便其他中间件
  14. //(例如,日志记录)可以在恢复状态下进行操作,而不会直接受到任何恐慌的影响
  15. _ = grpc.NewServer(
  16. grpc_middleware.WithUnaryServerChain(
  17. grpc_recovery.UnaryServerInterceptor(opts...),
  18. ),
  19. grpc_middleware.WithStreamServerChain(
  20. grpc_recovery.StreamServerInterceptor(opts...),
  21. ),
  22. )
  23. }