Debian Codegraph @

internal/gcerr/gcerr.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package gcerr provides an error type for Go CDK APIs.
16 package gcerr
17
18 import (
19 "context"
20 "errors"
21 "fmt"
22 "io"
23 "reflect"
24
25 "gocloud.dev/internal/retry"
26 "golang.org/x/xerrors"
27 "google.golang.org/grpc/codes"
28 "google.golang.org/grpc/status"
29 )
30
31 // An ErrorCode describes the error's category.
32 type ErrorCode int
33
34 const (
35 // OK is returned by the Code function on a nil error. It is not a valid
36 // code for an error.
37 OK ErrorCode = 0
38
39 // Unknown means that the error could not be categorized.
40 Unknown ErrorCode = 1
41
42 // NotFound means that the resource was not found.
43 NotFound ErrorCode = 2
44
45 // AlreadyExists means that the resource exists, but it should not.
46 AlreadyExists ErrorCode = 3
47
48 // InvalidArguments means that a value given to a Go CDK API is incorrect.
49 InvalidArgument ErrorCode = 4
50
51 // Internal means that something unexpected happened. Internal errors always indicate
52 // bugs in the Go CDK (or possibly the underlying service).
53 Internal ErrorCode = 5
54
55 // Unimplemented means that the feature is not implemented.
56 Unimplemented ErrorCode = 6
57
58 // FailedPrecondition means that the system was in the wrong state.
59 FailedPrecondition ErrorCode = 7
60
61 // PermissionDenied means that the caller does not have permission to execute the specified operation.
62 PermissionDenied ErrorCode = 8
63
64 // ResourceExhausted means that some resource has been exhausted, typically because a service resource limit
65 // has been reached.
66 ResourceExhausted ErrorCode = 9
67
68 // Canceled means that the operation was canceled.
69 Canceled ErrorCode = 10
70
71 // DeadlineExceeded means that The operation timed out.
72 DeadlineExceeded ErrorCode = 11
73 )
74
75 // When adding a new error code, try to use the names defined in google.golang.org/grpc/codes.
76
77 // Do not change the numbers assigned to codes: past values may be stored in metric databases.
78
79 // Call "go generate" whenever you change the above list of error codes.
80 // To get stringer:
81 // go get golang.org/x/tools/cmd/stringer
82 // Make sure $GOPATH/bin or $GOBIN in on your path.
83
84 //go:generate stringer -type=ErrorCode
85
86 // An Error describes a Go CDK error.
87 type Error struct {
88 // Code is the error code.
89 Code ErrorCode
90 msg string
91 frame xerrors.Frame
92 err error
93 }
94
95 // Error returns the error as a string.
96 func (e *Error) Error() string {
97 return fmt.Sprint(e)
98 }
99
100 // Format formats the error.
101 func (e *Error) Format(s fmt.State, c rune) {
102 xerrors.FormatError(e, s, c)
103 }
104
105 // FormatError formats the errots.
106 func (e *Error) FormatError(p xerrors.Printer) (next error) {
107 if e.msg == "" {
108 p.Printf("code=%v", e.Code)
109 } else {
110 p.Printf("%s (code=%v)", e.msg, e.Code)
111 }
112 e.frame.Format(p)
113 return e.err
114 }
115
116 // Unwrap returns the error underlying the receiver, which may be nil.
117 func (e *Error) Unwrap() error {
118 return e.err
119 }
120
121 // New returns a new error with the given code, underlying error and message. Pass 1
122 // for the call depth if New is called from the function raising the error; pass 2 if
123 // it is called from a helper function that was invoked by the original function; and
124 // so on.
125 func New(c ErrorCode, err error, callDepth int, msg string) *Error {
126 return &Error{
127 Code: c,
128 msg: msg,
129 frame: xerrors.Caller(callDepth),
130 err: err,
131 }
132 }
133
134 // Newf uses format and args to format a message, then calls New.
135 func Newf(c ErrorCode, err error, format string, args ...any) *Error {
136 return New(c, err, 2, fmt.Sprintf(format, args...))
137 }
138
139 // DoNotWrap reports whether an error should not be wrapped in the Error
140 // type from this package.
141 // It returns true if err is a retry error, a context error, io.EOF, or if it wraps
142 // one of those.
143 func DoNotWrap(err error) bool {
144 if errors.Is(err, io.EOF) {
145 return true
146 }
147 if errors.Is(err, context.Canceled) {
148 return true
149 }
150 if errors.Is(err, context.DeadlineExceeded) {
151 return true
152 }
153 var r *retry.ContextError
154 return errors.As(err, &r)
155 }
156
157 // GRPCCode extracts the gRPC status code and converts it into an ErrorCode.
158 // It returns Unknown if the error isn't from gRPC.
159 func GRPCCode(err error) ErrorCode {
160 switch status.Code(err) {
161 case codes.NotFound:
162 return NotFound
163 case codes.AlreadyExists:
164 return AlreadyExists
165 case codes.InvalidArgument:
166 return InvalidArgument
167 case codes.Internal:
168 return Internal
169 case codes.Unimplemented:
170 return Unimplemented
171 case codes.FailedPrecondition:
172 return FailedPrecondition
173 case codes.PermissionDenied:
174 return PermissionDenied
175 case codes.ResourceExhausted:
176 return ResourceExhausted
177 case codes.Canceled:
178 return Canceled
179 case codes.DeadlineExceeded:
180 return DeadlineExceeded
181 default:
182 return Unknown
183 }
184 }
185
186 // ErrorAs is a helper for the ErrorAs method of an API's portable type.
187 // It performs some initial nil checks, and does a single level of unwrapping
188 // when err is a *gcerr.Error. Then it calls its errorAs argument, which should
189 // be a driver implementation of ErrorAs.
190 func ErrorAs(err error, target any, errorAs func(error, any) bool) bool {
191 if err == nil {
192 return false
193 }
194 if target == nil {
195 panic("ErrorAs target cannot be nil")
196 }
197 val := reflect.ValueOf(target)
198 if val.Type().Kind() != reflect.Pointer || val.IsNil() {
199 panic("ErrorAs target must be a non-nil pointer")
200 }
201 if e, ok := err.(*Error); ok {
202 err = e.Unwrap()
203 }
204 return errorAs(err, target)
205 }