errors.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package otgrpc
  2. import (
  3. "github.com/opentracing/opentracing-go"
  4. "github.com/opentracing/opentracing-go/ext"
  5. "google.golang.org/grpc/codes"
  6. "google.golang.org/grpc/status"
  7. )
  8. // A Class is a set of types of outcomes (including errors) that will often
  9. // be handled in the same way.
  10. type Class string
  11. const (
  12. Unknown Class = "0xx"
  13. // Success represents outcomes that achieved the desired results.
  14. Success Class = "2xx"
  15. // ClientError represents errors that were the client's fault.
  16. ClientError Class = "4xx"
  17. // ServerError represents errors that were the server's fault.
  18. ServerError Class = "5xx"
  19. )
  20. // ErrorClass returns the class of the given error
  21. func ErrorClass(err error) Class {
  22. if s, ok := status.FromError(err); ok {
  23. switch s.Code() {
  24. // Success or "success"
  25. case codes.OK, codes.Canceled:
  26. return Success
  27. // Client errors
  28. case codes.InvalidArgument, codes.NotFound, codes.AlreadyExists,
  29. codes.PermissionDenied, codes.Unauthenticated, codes.FailedPrecondition,
  30. codes.OutOfRange:
  31. return ClientError
  32. // Server errors
  33. case codes.DeadlineExceeded, codes.ResourceExhausted, codes.Aborted,
  34. codes.Unimplemented, codes.Internal, codes.Unavailable, codes.DataLoss:
  35. return ServerError
  36. // Not sure
  37. case codes.Unknown:
  38. fallthrough
  39. default:
  40. return Unknown
  41. }
  42. }
  43. return Unknown
  44. }
  45. // SetSpanTags sets one or more tags on the given span according to the
  46. // error.
  47. func SetSpanTags(span opentracing.Span, err error, client bool) {
  48. c := ErrorClass(err)
  49. code := codes.Unknown
  50. if s, ok := status.FromError(err); ok {
  51. code = s.Code()
  52. }
  53. span.SetTag("response_code", code)
  54. span.SetTag("response_class", c)
  55. if err == nil {
  56. return
  57. }
  58. if client || c == ServerError {
  59. ext.Error.Set(span, true)
  60. }
  61. }