| 1 |
package grpcstatus |
| 2 |
|
| 3 |
import ( |
| 4 |
"google.golang.org/grpc/codes" |
| 5 |
"google.golang.org/grpc/status" |
| 6 |
) |
| 7 |
|
| 8 |
type gRPCStatus interface { |
| 9 |
GRPCStatus() *status.Status |
| 10 |
} |
| 11 |
|
| 12 |
func unwrapPkgErrorsGRPCStatus(err error) (*status.Status, bool) { |
| 13 |
type causer interface { |
| 14 |
Cause() error |
| 15 |
} |
| 16 |
|
| 17 |
// Unwrapping the github.com/pkg/errors causer interface, using `Cause` directly could miss some error implementing |
| 18 |
// the `GRPCStatus` function so we have to check it on our selves. |
| 19 |
unwrappedCauser := err |
| 20 |
for unwrappedCauser != nil { |
| 21 |
if s, ok := unwrappedCauser.(gRPCStatus); ok { |
| 22 |
return s.GRPCStatus(), true |
| 23 |
} |
| 24 |
cause, ok := unwrappedCauser.(causer) |
| 25 |
if !ok { |
| 26 |
break |
| 27 |
} |
| 28 |
unwrappedCauser = cause.Cause() |
| 29 |
} |
| 30 |
return nil, false |
| 31 |
} |
| 32 |
|
| 33 |
// Since error can be wrapped and the `FromError` function only checks for `GRPCStatus` function |
| 34 |
// and as a fallback uses the `Unknown` gRPC status we need to unwrap the error if possible to get the original status. |
| 35 |
// pkg/errors and Go native errors packages have two different approaches so we try to unwrap both types. |
| 36 |
// Eventually should be implemented in the go-grpc status function `FromError`. See https://github.com/grpc/grpc-go/issues/2934 |
| 37 |
func FromError(err error) (s *status.Status, ok bool) { |
| 38 |
s, ok = status.FromError(err) |
| 39 |
if ok { |
| 40 |
return s, true |
| 41 |
} |
| 42 |
|
| 43 |
// Try to unwrap `github.com/pkg/errors` wrapped error |
| 44 |
s, ok = unwrapPkgErrorsGRPCStatus(err) |
| 45 |
if ok { |
| 46 |
return s, true |
| 47 |
} |
| 48 |
|
| 49 |
// Try to unwrap native wrapped errors using `fmt.Errorf` and `%w` |
| 50 |
s, ok = unwrapNativeWrappedGRPCStatus(err) |
| 51 |
if ok { |
| 52 |
return s, true |
| 53 |
} |
| 54 |
|
| 55 |
// We failed to unwrap any GRPSStatus so return default `Unknown` |
| 56 |
return status.New(codes.Unknown, err.Error()), false |
| 57 |
} |