crashinterceptor.go 985 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package serverinterceptors
  2. import (
  3. "context"
  4. "runtime/debug"
  5. "github.com/tal-tech/go-zero/core/logx"
  6. "google.golang.org/grpc"
  7. "google.golang.org/grpc/codes"
  8. "google.golang.org/grpc/status"
  9. )
  10. func StreamCrashInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo,
  11. handler grpc.StreamHandler) (err error) {
  12. defer handleCrash(func(r interface{}) {
  13. err = toPanicError(r)
  14. })
  15. return handler(srv, stream)
  16. }
  17. func UnaryCrashInterceptor() grpc.UnaryServerInterceptor {
  18. return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
  19. handler grpc.UnaryHandler) (resp interface{}, err error) {
  20. defer handleCrash(func(r interface{}) {
  21. err = toPanicError(r)
  22. })
  23. return handler(ctx, req)
  24. }
  25. }
  26. func handleCrash(handler func(interface{})) {
  27. if r := recover(); r != nil {
  28. handler(r)
  29. }
  30. }
  31. func toPanicError(r interface{}) error {
  32. logx.Errorf("%+v %s", r, debug.Stack())
  33. return status.Errorf(codes.Internal, "panic: %v", r)
  34. }