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
?
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)
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments