error.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package grpcutil
  2. import (
  3. "errors"
  4. "reflect"
  5. "kpt-grpc-demo/util/xerr"
  6. spb "google.golang.org/genproto/googleapis/rpc/status"
  7. "google.golang.org/grpc/codes"
  8. "google.golang.org/grpc/status"
  9. )
  10. // StatusError cause of grpc status error
  11. func StatusError(err error) (*status.Status, bool) {
  12. statusErr, ok := status.FromError(xerr.Cause(err))
  13. if !ok {
  14. return nil, false
  15. }
  16. return statusErr, true
  17. }
  18. // FilterServerError 优化服务端错误上报逻辑
  19. func FilterServerError(err error) bool {
  20. statusErr, ok := StatusError(err)
  21. if !ok {
  22. return true
  23. }
  24. details := statusErr.Details()
  25. for _, detail := range details {
  26. if _, ok := detail.(*spb.Status); ok && statusErr.Code() != codes.Canceled {
  27. return false
  28. }
  29. }
  30. ignoreStatus := []codes.Code{codes.InvalidArgument, codes.Unauthenticated, codes.NotFound, codes.FailedPrecondition, codes.AlreadyExists}
  31. if inArray, _ := In(statusErr.Code(), ignoreStatus); inArray {
  32. return false
  33. }
  34. return true
  35. }
  36. func In(obj interface{}, target interface{}) (bool, error) {
  37. targetValue := reflect.ValueOf(target)
  38. switch reflect.TypeOf(target).Kind() {
  39. case reflect.Slice, reflect.Array:
  40. for i := 0; i < targetValue.Len(); i++ {
  41. if targetValue.Index(i).Interface() == obj {
  42. return true, nil
  43. }
  44. }
  45. case reflect.Map:
  46. if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
  47. return true, nil
  48. }
  49. }
  50. return false, errors.New("not in array")
  51. }