Joe Tsai | 9834a7d | 2018-08-01 13:16:49 -0700 | [diff] [blame] | 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 | |
| 5 | // Package errors implements functions to manipulate errors. |
| 6 | package errors |
| 7 | |
| 8 | import ( |
| 9 | "fmt" |
Joe Tsai | 09217f0 | 2019-09-06 16:57:46 -0700 | [diff] [blame] | 10 | |
| 11 | "google.golang.org/protobuf/internal/detrand" |
Joe Tsai | 9834a7d | 2018-08-01 13:16:49 -0700 | [diff] [blame] | 12 | ) |
| 13 | |
Joe Tsai | 9834a7d | 2018-08-01 13:16:49 -0700 | [diff] [blame] | 14 | // New formats a string according to the format specifier and arguments and |
| 15 | // returns an error that has a "proto" prefix. |
| 16 | func New(f string, x ...interface{}) error { |
| 17 | for i := 0; i < len(x); i++ { |
Herbie Ong | e09920e | 2019-02-27 13:37:06 -0800 | [diff] [blame] | 18 | if e, ok := x[i].(*prefixError); ok { |
Joe Tsai | 9834a7d | 2018-08-01 13:16:49 -0700 | [diff] [blame] | 19 | x[i] = e.s // avoid "proto: " prefix when chaining |
| 20 | } |
| 21 | } |
| 22 | return &prefixError{s: fmt.Sprintf(f, x...)} |
| 23 | } |
| 24 | |
| 25 | type prefixError struct{ s string } |
| 26 | |
Joe Tsai | 09217f0 | 2019-09-06 16:57:46 -0700 | [diff] [blame] | 27 | var prefix = func() string { |
Joe Tsai | 27af11f | 2019-09-07 12:06:05 -0700 | [diff] [blame] | 28 | // Deliberately introduce instability into the error message string to |
| 29 | // discourage users from performing error string comparisons. |
Joe Tsai | 09217f0 | 2019-09-06 16:57:46 -0700 | [diff] [blame] | 30 | if detrand.Bool() { |
Joe Tsai | 27af11f | 2019-09-07 12:06:05 -0700 | [diff] [blame] | 31 | return "proto: " // use non-breaking spaces (U+00a0) |
| 32 | } else { |
| 33 | return "proto: " // use regular spaces (U+0020) |
Joe Tsai | 09217f0 | 2019-09-06 16:57:46 -0700 | [diff] [blame] | 34 | } |
Joe Tsai | 09217f0 | 2019-09-06 16:57:46 -0700 | [diff] [blame] | 35 | }() |
| 36 | |
| 37 | func (e *prefixError) Error() string { |
| 38 | return prefix + e.s |
| 39 | } |
Damien Neil | 8c86fc5 | 2019-06-19 09:28:29 -0700 | [diff] [blame] | 40 | |
| 41 | func InvalidUTF8(name string) error { |
| 42 | return New("field %v contains invalid UTF-8", name) |
| 43 | } |
| 44 | |
| 45 | func RequiredNotSet(name string) error { |
| 46 | return New("required field %v not set", name) |
| 47 | } |