You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

55 lines
1.6 KiB

  1. // Copyright 2017 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package internal
  15. import (
  16. "fmt"
  17. "google.golang.org/api/googleapi"
  18. "google.golang.org/grpc/status"
  19. )
  20. // Annotate prepends msg to the error message in err, attempting
  21. // to preserve other information in err, like an error code.
  22. //
  23. // Annotate panics if err is nil.
  24. //
  25. // Annotate knows about these error types:
  26. // - "google.golang.org/grpc/status".Status
  27. // - "google.golang.org/api/googleapi".Error
  28. // If the error is not one of these types, Annotate behaves
  29. // like
  30. // fmt.Errorf("%s: %v", msg, err)
  31. func Annotate(err error, msg string) error {
  32. if err == nil {
  33. panic("Annotate called with nil")
  34. }
  35. if s, ok := status.FromError(err); ok {
  36. p := s.Proto()
  37. p.Message = msg + ": " + p.Message
  38. return status.ErrorProto(p)
  39. }
  40. if g, ok := err.(*googleapi.Error); ok {
  41. g.Message = msg + ": " + g.Message
  42. return g
  43. }
  44. return fmt.Errorf("%s: %v", msg, err)
  45. }
  46. // Annotatef uses format and args to format a string, then calls Annotate.
  47. func Annotatef(err error, format string, args ...interface{}) error {
  48. return Annotate(err, fmt.Sprintf(format, args...))
  49. }