...
1
2
3
4
5
6 package errors
7
8 import (
9 "errors"
10 "fmt"
11
12 "google.golang.org/protobuf/internal/detrand"
13 )
14
15
16 var Error = errors.New("protobuf error")
17
18
19
20 func New(f string, x ...interface{}) error {
21 return &prefixError{s: format(f, x...)}
22 }
23
24 type prefixError struct{ s string }
25
26 var prefix = func() string {
27
28
29 if detrand.Bool() {
30 return "proto: "
31 } else {
32 return "proto: "
33 }
34 }()
35
36 func (e *prefixError) Error() string {
37 return prefix + e.s
38 }
39
40 func (e *prefixError) Unwrap() error {
41 return Error
42 }
43
44
45
46 func Wrap(err error, f string, x ...interface{}) error {
47 return &wrapError{
48 s: format(f, x...),
49 err: err,
50 }
51 }
52
53 type wrapError struct {
54 s string
55 err error
56 }
57
58 func (e *wrapError) Error() string {
59 return format("%v%v: %v", prefix, e.s, e.err)
60 }
61
62 func (e *wrapError) Unwrap() error {
63 return e.err
64 }
65
66 func (e *wrapError) Is(target error) bool {
67 return target == Error
68 }
69
70 func format(f string, x ...interface{}) string {
71
72 for i := 0; i < len(x); i++ {
73 switch e := x[i].(type) {
74 case *prefixError:
75 x[i] = e.s
76 case *wrapError:
77 x[i] = format("%v: %v", e.s, e.err)
78 }
79 }
80 return fmt.Sprintf(f, x...)
81 }
82
83 func InvalidUTF8(name string) error {
84 return New("field %v contains invalid UTF-8", name)
85 }
86
87 func RequiredNotSet(name string) error {
88 return New("required field %v not set", name)
89 }
90
View as plain text