blob: bc495b49aec9af498fd7b18d97420c40bd008e9d [file] [log] [blame]
Joe Tsai9834a7d2018-08-01 13:16:49 -07001// 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.
6package errors
7
8import (
9 "fmt"
Joe Tsai09217f02019-09-06 16:57:46 -070010
11 "google.golang.org/protobuf/internal/detrand"
Joe Tsai9834a7d2018-08-01 13:16:49 -070012)
13
Joe Tsai9834a7d2018-08-01 13:16:49 -070014// New formats a string according to the format specifier and arguments and
15// returns an error that has a "proto" prefix.
16func New(f string, x ...interface{}) error {
17 for i := 0; i < len(x); i++ {
Herbie Onge09920e2019-02-27 13:37:06 -080018 if e, ok := x[i].(*prefixError); ok {
Joe Tsai9834a7d2018-08-01 13:16:49 -070019 x[i] = e.s // avoid "proto: " prefix when chaining
20 }
21 }
22 return &prefixError{s: fmt.Sprintf(f, x...)}
23}
24
25type prefixError struct{ s string }
26
Joe Tsai09217f02019-09-06 16:57:46 -070027var prefix = func() string {
Joe Tsai27af11f2019-09-07 12:06:05 -070028 // Deliberately introduce instability into the error message string to
29 // discourage users from performing error string comparisons.
Joe Tsai09217f02019-09-06 16:57:46 -070030 if detrand.Bool() {
Joe Tsai27af11f2019-09-07 12:06:05 -070031 return "proto: " // use non-breaking spaces (U+00a0)
32 } else {
33 return "proto: " // use regular spaces (U+0020)
Joe Tsai09217f02019-09-06 16:57:46 -070034 }
Joe Tsai09217f02019-09-06 16:57:46 -070035}()
36
37func (e *prefixError) Error() string {
38 return prefix + e.s
39}
Damien Neil8c86fc52019-06-19 09:28:29 -070040
41func InvalidUTF8(name string) error {
42 return New("field %v contains invalid UTF-8", name)
43}
44
45func RequiredNotSet(name string) error {
46 return New("required field %v not set", name)
47}