1// Copyright 2017 David Ackroyd. All Rights Reserved. 2// See LICENSE for licensing terms. 3 4package grpc_recovery_test 5 6import ( 7 "github.com/grpc-ecosystem/go-grpc-middleware" 8 "github.com/grpc-ecosystem/go-grpc-middleware/recovery" 9 "google.golang.org/grpc" 10 "google.golang.org/grpc/codes" 11 "google.golang.org/grpc/status" 12) 13 14var ( 15 customFunc grpc_recovery.RecoveryHandlerFunc 16) 17 18// Initialization shows an initialization sequence with a custom recovery handler func. 19func Example_initialization() { 20 // Define customfunc to handle panic 21 customFunc = func(p interface{}) (err error) { 22 return status.Errorf(codes.Unknown, "panic triggered: %v", p) 23 } 24 // Shared options for the logger, with a custom gRPC code to log level function. 25 opts := []grpc_recovery.Option{ 26 grpc_recovery.WithRecoveryHandler(customFunc), 27 } 28 // Create a server. Recovery handlers should typically be last in the chain so that other middleware 29 // (e.g. logging) can operate on the recovered state instead of being directly affected by any panic 30 _ = grpc.NewServer( 31 grpc_middleware.WithUnaryServerChain( 32 grpc_recovery.UnaryServerInterceptor(opts...), 33 ), 34 grpc_middleware.WithStreamServerChain( 35 grpc_recovery.StreamServerInterceptor(opts...), 36 ), 37 ) 38} 39