Given the following gRPC server side code:
import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
....
)
....
func (s *Router) Assign(ctx context.Context, req *api.Request(*api.Response, error) {
return nil, status.Errorf(codes.PermissionDenied,
}
....
What is the recommended technique for asserting client side that the error is of code = codes.PermissionDenied
?
If an error occurs, gRPC returns one of its error status codes instead, with an optional string error message that provides further details about what happened. Error information is available to gRPC clients in all supported languages.
7. The caller does not have permission to execute the specified operation. PERMISSION_DENIED must not be used for rejections caused by exhausting some resource (use RESOURCE_EXHAUSTED instead for those errors).
Let's say your server returns codes.PermissionDenined
like this
...
return nil, status.Error(codes.PermissionDenied, "PERMISSION_DENIED_TEXT")
If your client is Golang as well can also use the status
library function FromError
to parse the error. I use a switch to determine the error code returned like so
// client
assignvar, err := s.MyFunctionCall(ctx, ...)
if err != nil {
if e, ok := status.FromError(err); ok {
switch e.Code() {
case codes.PermissionDenied:
fmt.Println(e.Message()) // this will print PERMISSION_DENIED_TEST
case codes.Internal:
fmt.Println("Has Internal Error")
case codes.Aborted:
fmt.Println("gRPC Aborted the call")
default:
fmt.Println(e.Code(), e.Message())
}
}
else {
fmt.Printf("not able to parse error returned %v", err)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With