原理:
使用status包对grpc内的错误进行识别!
代码:
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: "world"})if err != nil {s := status.Convert(err)for _, d := range s.Details() {switch info := d.(type) {case *epb.QuotaFailure:log.Printf("Quota failure: %s", info)default:log.Printf("Unexpected type: %s", info)}}os.Exit(1)}
服务端:
st := status.New(codes.ResourceExhausted, "Request limit exceeded.")
ds, err := st.WithDetails(
&epb.QuotaFailure{
Violations: []*epb.QuotaFailure_Violation{{
Subject: fmt.Sprintf("name:%s", in.Name),
Description: "Limit one greeting per person",
}},
},
)
if err != nil {
return nil, st.Err()
}
