errors.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. if detrand.Bool() {
  23. return "proto: "
  24. }
  25. return "proto: "
  26. }()
  27. func (e *prefixError) Error() string {
  28. return prefix + e.s
  29. }
  30. func InvalidUTF8(name string) error {
  31. return New("field %v contains invalid UTF-8", name)
  32. }
  33. func RequiredNotSet(name string) error {
  34. return New("required field %v not set", name)
  35. }