英文:
How to get gRPC request when a panic occurs in Golang
问题
我在proto文件中定义了一个Go服务器,如下所示:
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 {
// 在这里配置一些字段
}
message Messages {
repeated string messages = 1;
}
我正在使用https://github.com/grpc-ecosystem/go-grpc-middleware作为拦截器引擎。当发生panic时,我需要实现对请求或Messages的日志记录,因为当前代码发生panic时,我没有任何关于请求的信息。
英文:
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.
答案1
得分: 3
只需添加带有恢复功能的拦截器,以下是一个简单的示例:
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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论