ardianbsyla
ardianbsyla

Reputation: 93

How to get gRPC request when a panic occurs in Golang

I have a Go server defined like this in proto file:

syntax = "proto3";

package go-package;

option go_package = "github.com/path/to/go-package";

import "vibe.proto";

service MyService {
  rpc Function (stream TheRequest) returns (stream TheResponse) {}
}

message TheRequest {
  oneof Payload {
    Config config = 1;
    Messages messages = 2;
  }
}

message Config {
  // config some fields here
}

message Messages {
  repeated string messages = 1;
}

I'm using https://github.com/grpc-ecosystem/go-grpc-middleware as an interceptor engine. I need to implement logging of the request or Messages when I have a panic, because right now the code is panicked, but i don't have any information about the request.

Upvotes: 1

Views: 694

Answers (1)

thrownew
thrownew

Reputation: 115

Just add interceptor with recovery, simple example:

func RecoveryUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
    defer func() {
        if r := recover(); r != nil {
            err = status.Error(codes.Internal, fmt.Sprintf("Panic: `%s` %s", info.FullMethod, string(debug.Stack())))
        }
    }()
    return handler(ctx, req)
}

Upvotes: 3

Related Questions