errors.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package errors implements functions to manipulate errors.
  5. package errors
  6. import (
  7. "fmt"
  8. "google.golang.org/protobuf/internal/detrand"
  9. )
  10. // New formats a string according to the format specifier and arguments and
  11. // returns an error that has a "proto" prefix.
  12. func New(f string, x ...interface{}) error {
  13. for i := 0; i < len(x); i++ {
  14. if e, ok := x[i].(*prefixError); ok {
  15. x[i] = e.s // avoid "proto: " prefix when chaining
  16. }
  17. }
  18. return &prefixError{s: fmt.Sprintf(f, x...)}
  19. }
  20. type prefixError struct{ s string }
  21. var prefix = func() string {
  22. // Deliberately introduce instability into the error message string to
  23. // discourage users from performing error string comparisons.
  24. if detrand.Bool() {
  25. return "proto: " // use non-breaking spaces (U+00a0)
  26. } else {
  27. return "proto: " // use regular spaces (U+0020)
  28. }
  29. }()
  30. func (e *prefixError) Error() string {
  31. return prefix + e.s
  32. }
  33. func InvalidUTF8(name string) error {
  34. return New("field %v contains invalid UTF-8", name)
  35. }
  36. func RequiredNotSet(name string) error {
  37. return New("required field %v not set", name)
  38. }