Here is something I did to pass custom error information:
Based on the grpc code, if an error type has GRPCStatus()
*status.Status function, then grpc gets the status information using
that method. For the error types that can go through grpc, I have this
method below:
func (e MyError) GRPCStatus() *status.Status {
var code codes.Code
switch e.HTTPStatus {
case http.StatusBadRequest:
code = codes.InvalidArgument
case http.StatusUnauthorized:
code = codes.Unauthenticated
default:
code = codes.Unknown
}
x, _ := json.Marshal(e)
return status.New(code, string(x))
}
In this example, the error type includes an HTTP status code, and the
grpc status is decided based on that. The grpc error contains a JSON
marshaled error information.
On the receiving end, I have this function:
func FromGRPCError(err error) (MyError, bool) {
if x, ok := status.FromError(err); ok {
var e MyError
if json.Unmarshal([]byte(x.Message()), &e) == nil {
return e, true
}
}
return MyError{}, false
}
This decodes the error information from the incoming error.
This scheme can be extended to deal with multiple error types.
> To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/CAEkBMfERsv28%2BJV-EVYqhZraHbyYmPftQV6V0i55zVaK1R13HQ%40mail.gmail.com.