| 1 |
// Copyright 2021, Google Inc. |
| 2 |
// All rights reserved. |
| 3 |
// |
| 4 |
// Redistribution and use in source and binary forms, with or without |
| 5 |
// modification, are permitted provided that the following conditions are |
| 6 |
// met: |
| 7 |
// |
| 8 |
// * Redistributions of source code must retain the above copyright |
| 9 |
// notice, this list of conditions and the following disclaimer. |
| 10 |
// * Redistributions in binary form must reproduce the above |
| 11 |
// copyright notice, this list of conditions and the following disclaimer |
| 12 |
// in the documentation and/or other materials provided with the |
| 13 |
// distribution. |
| 14 |
// * Neither the name of Google Inc. nor the names of its |
| 15 |
// contributors may be used to endorse or promote products derived from |
| 16 |
// this software without specific prior written permission. |
| 17 |
// |
| 18 |
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 19 |
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 20 |
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 21 |
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 22 |
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 |
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 24 |
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 25 |
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 26 |
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 |
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 |
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 |
|
| 30 |
// Package apierror implements a wrapper error for parsing error details from |
| 31 |
// API calls. Both HTTP & gRPC status errors are supported. |
| 32 |
// |
| 33 |
// For examples of how to use [APIError] with client libraries please reference |
| 34 |
// [Inspecting errors](https://pkg.go.dev/cloud.google.com/go#hdr-Inspecting_errors) |
| 35 |
// in the client library documentation. |
| 36 |
package apierror |
| 37 |
|
| 38 |
import ( |
| 39 |
"errors" |
| 40 |
"fmt" |
| 41 |
"strings" |
| 42 |
|
| 43 |
jsonerror "github.com/googleapis/gax-go/v2/apierror/internal/proto" |
| 44 |
"google.golang.org/api/googleapi" |
| 45 |
"google.golang.org/genproto/googleapis/rpc/errdetails" |
| 46 |
"google.golang.org/grpc/codes" |
| 47 |
"google.golang.org/grpc/status" |
| 48 |
"google.golang.org/protobuf/encoding/protojson" |
| 49 |
"google.golang.org/protobuf/proto" |
| 50 |
) |
| 51 |
|
| 52 |
// ErrDetails holds the google/rpc/error_details.proto messages. |
| 53 |
type ErrDetails struct { |
| 54 |
ErrorInfo *errdetails.ErrorInfo |
| 55 |
BadRequest *errdetails.BadRequest |
| 56 |
PreconditionFailure *errdetails.PreconditionFailure |
| 57 |
QuotaFailure *errdetails.QuotaFailure |
| 58 |
RetryInfo *errdetails.RetryInfo |
| 59 |
ResourceInfo *errdetails.ResourceInfo |
| 60 |
RequestInfo *errdetails.RequestInfo |
| 61 |
DebugInfo *errdetails.DebugInfo |
| 62 |
Help *errdetails.Help |
| 63 |
LocalizedMessage *errdetails.LocalizedMessage |
| 64 |
|
| 65 |
// Unknown stores unidentifiable error details. |
| 66 |
Unknown []interface{} |
| 67 |
} |
| 68 |
|
| 69 |
// ErrMessageNotFound is used to signal ExtractProtoMessage found no matching messages. |
| 70 |
var ErrMessageNotFound = errors.New("message not found") |
| 71 |
|
| 72 |
// ExtractProtoMessage provides a mechanism for extracting protobuf messages from the |
| 73 |
// Unknown error details. If ExtractProtoMessage finds an unknown message of the same type, |
| 74 |
// the content of the message is copied to the provided message. |
| 75 |
// |
| 76 |
// ExtractProtoMessage will return ErrMessageNotFound if there are no message matching the |
| 77 |
// protocol buffer type of the provided message. |
| 78 |
func (e ErrDetails) ExtractProtoMessage(v proto.Message) error { |
| 79 |
if v == nil { |
| 80 |
return ErrMessageNotFound |
| 81 |
} |
| 82 |
for _, elem := range e.Unknown { |
| 83 |
if elemProto, ok := elem.(proto.Message); ok { |
| 84 |
if v.ProtoReflect().Type() == elemProto.ProtoReflect().Type() { |
| 85 |
proto.Merge(v, elemProto) |
| 86 |
return nil |
| 87 |
} |
| 88 |
} |
| 89 |
} |
| 90 |
return ErrMessageNotFound |
| 91 |
} |
| 92 |
|
| 93 |
func (e ErrDetails) String() string { |
| 94 |
var d strings.Builder |
| 95 |
if e.ErrorInfo != nil { |
| 96 |
d.WriteString(fmt.Sprintf("error details: name = ErrorInfo reason = %s domain = %s metadata = %s\n", |
| 97 |
e.ErrorInfo.GetReason(), e.ErrorInfo.GetDomain(), e.ErrorInfo.GetMetadata())) |
| 98 |
} |
| 99 |
|
| 100 |
if e.BadRequest != nil { |
| 101 |
v := e.BadRequest.GetFieldViolations() |
| 102 |
var f []string |
| 103 |
var desc []string |
| 104 |
for _, x := range v { |
| 105 |
f = append(f, x.GetField()) |
| 106 |
desc = append(desc, x.GetDescription()) |
| 107 |
} |
| 108 |
d.WriteString(fmt.Sprintf("error details: name = BadRequest field = %s desc = %s\n", |
| 109 |
strings.Join(f, " "), strings.Join(desc, " "))) |
| 110 |
} |
| 111 |
|
| 112 |
if e.PreconditionFailure != nil { |
| 113 |
v := e.PreconditionFailure.GetViolations() |
| 114 |
var t []string |
| 115 |
var s []string |
| 116 |
var desc []string |
| 117 |
for _, x := range v { |
| 118 |
t = append(t, x.GetType()) |
| 119 |
s = append(s, x.GetSubject()) |
| 120 |
desc = append(desc, x.GetDescription()) |
| 121 |
} |
| 122 |
d.WriteString(fmt.Sprintf("error details: name = PreconditionFailure type = %s subj = %s desc = %s\n", strings.Join(t, " "), |
| 123 |
strings.Join(s, " "), strings.Join(desc, " "))) |
| 124 |
} |
| 125 |
|
| 126 |
if e.QuotaFailure != nil { |
| 127 |
v := e.QuotaFailure.GetViolations() |
| 128 |
var s []string |
| 129 |
var desc []string |
| 130 |
for _, x := range v { |
| 131 |
s = append(s, x.GetSubject()) |
| 132 |
desc = append(desc, x.GetDescription()) |
| 133 |
} |
| 134 |
d.WriteString(fmt.Sprintf("error details: name = QuotaFailure subj = %s desc = %s\n", |
| 135 |
strings.Join(s, " "), strings.Join(desc, " "))) |
| 136 |
} |
| 137 |
|
| 138 |
if e.RequestInfo != nil { |
| 139 |
d.WriteString(fmt.Sprintf("error details: name = RequestInfo id = %s data = %s\n", |
| 140 |
e.RequestInfo.GetRequestId(), e.RequestInfo.GetServingData())) |
| 141 |
} |
| 142 |
|
| 143 |
if e.ResourceInfo != nil { |
| 144 |
d.WriteString(fmt.Sprintf("error details: name = ResourceInfo type = %s resourcename = %s owner = %s desc = %s\n", |
| 145 |
e.ResourceInfo.GetResourceType(), e.ResourceInfo.GetResourceName(), |
| 146 |
e.ResourceInfo.GetOwner(), e.ResourceInfo.GetDescription())) |
| 147 |
|
| 148 |
} |
| 149 |
if e.RetryInfo != nil { |
| 150 |
d.WriteString(fmt.Sprintf("error details: retry in %s\n", e.RetryInfo.GetRetryDelay().AsDuration())) |
| 151 |
|
| 152 |
} |
| 153 |
if e.Unknown != nil { |
| 154 |
var s []string |
| 155 |
for _, x := range e.Unknown { |
| 156 |
s = append(s, fmt.Sprintf("%v", x)) |
| 157 |
} |
| 158 |
d.WriteString(fmt.Sprintf("error details: name = Unknown desc = %s\n", strings.Join(s, " "))) |
| 159 |
} |
| 160 |
|
| 161 |
if e.DebugInfo != nil { |
| 162 |
d.WriteString(fmt.Sprintf("error details: name = DebugInfo detail = %s stack = %s\n", e.DebugInfo.GetDetail(), |
| 163 |
strings.Join(e.DebugInfo.GetStackEntries(), " "))) |
| 164 |
} |
| 165 |
if e.Help != nil { |
| 166 |
var desc []string |
| 167 |
var url []string |
| 168 |
for _, x := range e.Help.Links { |
| 169 |
desc = append(desc, x.GetDescription()) |
| 170 |
url = append(url, x.GetUrl()) |
| 171 |
} |
| 172 |
d.WriteString(fmt.Sprintf("error details: name = Help desc = %s url = %s\n", |
| 173 |
strings.Join(desc, " "), strings.Join(url, " "))) |
| 174 |
} |
| 175 |
if e.LocalizedMessage != nil { |
| 176 |
d.WriteString(fmt.Sprintf("error details: name = LocalizedMessage locale = %s msg = %s\n", |
| 177 |
e.LocalizedMessage.GetLocale(), e.LocalizedMessage.GetMessage())) |
| 178 |
} |
| 179 |
|
| 180 |
return d.String() |
| 181 |
} |
| 182 |
|
| 183 |
// APIError wraps either a gRPC Status error or a HTTP googleapi.Error. It |
| 184 |
// implements error and Status interfaces. |
| 185 |
type APIError struct { |
| 186 |
err error |
| 187 |
status *status.Status |
| 188 |
httpErr *googleapi.Error |
| 189 |
details ErrDetails |
| 190 |
} |
| 191 |
|
| 192 |
// Details presents the error details of the APIError. |
| 193 |
func (a *APIError) Details() ErrDetails { |
| 194 |
return a.details |
| 195 |
} |
| 196 |
|
| 197 |
// Unwrap extracts the original error. |
| 198 |
func (a *APIError) Unwrap() error { |
| 199 |
return a.err |
| 200 |
} |
| 201 |
|
| 202 |
// Error returns a readable representation of the APIError. |
| 203 |
func (a *APIError) Error() string { |
| 204 |
var msg string |
| 205 |
if a.httpErr != nil { |
| 206 |
// Truncate the googleapi.Error message because it dumps the Details in |
| 207 |
// an ugly way. |
| 208 |
msg = fmt.Sprintf("googleapi: Error %d: %s", a.httpErr.Code, a.httpErr.Message) |
| 209 |
} else if a.status != nil && a.err != nil { |
| 210 |
msg = a.err.Error() |
| 211 |
} else if a.status != nil { |
| 212 |
msg = a.status.Message() |
| 213 |
} |
| 214 |
return strings.TrimSpace(fmt.Sprintf("%s\n%s", msg, a.details)) |
| 215 |
} |
| 216 |
|
| 217 |
// GRPCStatus extracts the underlying gRPC Status error. |
| 218 |
// This method is necessary to fulfill the interface |
| 219 |
// described in https://pkg.go.dev/google.golang.org/grpc/status#FromError. |
| 220 |
func (a *APIError) GRPCStatus() *status.Status { |
| 221 |
return a.status |
| 222 |
} |
| 223 |
|
| 224 |
// Reason returns the reason in an ErrorInfo. |
| 225 |
// If ErrorInfo is nil, it returns an empty string. |
| 226 |
func (a *APIError) Reason() string { |
| 227 |
return a.details.ErrorInfo.GetReason() |
| 228 |
} |
| 229 |
|
| 230 |
// Domain returns the domain in an ErrorInfo. |
| 231 |
// If ErrorInfo is nil, it returns an empty string. |
| 232 |
func (a *APIError) Domain() string { |
| 233 |
return a.details.ErrorInfo.GetDomain() |
| 234 |
} |
| 235 |
|
| 236 |
// Metadata returns the metadata in an ErrorInfo. |
| 237 |
// If ErrorInfo is nil, it returns nil. |
| 238 |
func (a *APIError) Metadata() map[string]string { |
| 239 |
return a.details.ErrorInfo.GetMetadata() |
| 240 |
|
| 241 |
} |
| 242 |
|
| 243 |
// setDetailsFromError parses a Status error or a googleapi.Error |
| 244 |
// and sets status and details or httpErr and details, respectively. |
| 245 |
// It returns false if neither Status nor googleapi.Error can be parsed. |
| 246 |
// When err is a googleapi.Error, the status of the returned error will |
| 247 |
// be set to an Unknown error, rather than nil, since a nil code is |
| 248 |
// interpreted as OK in the gRPC status package. |
| 249 |
func (a *APIError) setDetailsFromError(err error) bool { |
| 250 |
st, isStatus := status.FromError(err) |
| 251 |
var herr *googleapi.Error |
| 252 |
isHTTPErr := errors.As(err, &herr) |
| 253 |
|
| 254 |
switch { |
| 255 |
case isStatus: |
| 256 |
a.status = st |
| 257 |
a.details = parseDetails(st.Details()) |
| 258 |
case isHTTPErr: |
| 259 |
a.httpErr = herr |
| 260 |
a.details = parseHTTPDetails(herr) |
| 261 |
a.status = status.New(codes.Unknown, herr.Message) |
| 262 |
default: |
| 263 |
return false |
| 264 |
} |
| 265 |
return true |
| 266 |
} |
| 267 |
|
| 268 |
// FromError parses a Status error or a googleapi.Error and builds an |
| 269 |
// APIError, wrapping the provided error in the new APIError. It |
| 270 |
// returns false if neither Status nor googleapi.Error can be parsed. |
| 271 |
func FromError(err error) (*APIError, bool) { |
| 272 |
return ParseError(err, true) |
| 273 |
} |
| 274 |
|
| 275 |
// ParseError parses a Status error or a googleapi.Error and builds an |
| 276 |
// APIError. If wrap is true, it wraps the error in the new APIError. |
| 277 |
// It returns false if neither Status nor googleapi.Error can be parsed. |
| 278 |
func ParseError(err error, wrap bool) (*APIError, bool) { |
| 279 |
if err == nil { |
| 280 |
return nil, false |
| 281 |
} |
| 282 |
ae := APIError{} |
| 283 |
if wrap { |
| 284 |
ae = APIError{err: err} |
| 285 |
} |
| 286 |
if !ae.setDetailsFromError(err) { |
| 287 |
return nil, false |
| 288 |
} |
| 289 |
return &ae, true |
| 290 |
} |
| 291 |
|
| 292 |
// parseDetails accepts a slice of interface{} that should be backed by some |
| 293 |
// sort of proto.Message that can be cast to the google/rpc/error_details.proto |
| 294 |
// types. |
| 295 |
// |
| 296 |
// This is for internal use only. |
| 297 |
func parseDetails(details []interface{}) ErrDetails { |
| 298 |
var ed ErrDetails |
| 299 |
for _, d := range details { |
| 300 |
switch d := d.(type) { |
| 301 |
case *errdetails.ErrorInfo: |
| 302 |
ed.ErrorInfo = d |
| 303 |
case *errdetails.BadRequest: |
| 304 |
ed.BadRequest = d |
| 305 |
case *errdetails.PreconditionFailure: |
| 306 |
ed.PreconditionFailure = d |
| 307 |
case *errdetails.QuotaFailure: |
| 308 |
ed.QuotaFailure = d |
| 309 |
case *errdetails.RetryInfo: |
| 310 |
ed.RetryInfo = d |
| 311 |
case *errdetails.ResourceInfo: |
| 312 |
ed.ResourceInfo = d |
| 313 |
case *errdetails.RequestInfo: |
| 314 |
ed.RequestInfo = d |
| 315 |
case *errdetails.DebugInfo: |
| 316 |
ed.DebugInfo = d |
| 317 |
case *errdetails.Help: |
| 318 |
ed.Help = d |
| 319 |
case *errdetails.LocalizedMessage: |
| 320 |
ed.LocalizedMessage = d |
| 321 |
default: |
| 322 |
ed.Unknown = append(ed.Unknown, d) |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
return ed |
| 327 |
} |
| 328 |
|
| 329 |
// parseHTTPDetails will convert the given googleapi.Error into the protobuf |
| 330 |
// representation then parse the Any values that contain the error details. |
| 331 |
// |
| 332 |
// This is for internal use only. |
| 333 |
func parseHTTPDetails(gae *googleapi.Error) ErrDetails { |
| 334 |
e := &jsonerror.Error{} |
| 335 |
if err := protojson.Unmarshal([]byte(gae.Body), e); err != nil { |
| 336 |
// If the error body does not conform to the error schema, ignore it |
| 337 |
// altogther. See https://cloud.google.com/apis/design/errors#http_mapping. |
| 338 |
return ErrDetails{} |
| 339 |
} |
| 340 |
|
| 341 |
// Coerce the Any messages into proto.Message then parse the details. |
| 342 |
details := []interface{}{} |
| 343 |
for _, any := range e.GetError().GetDetails() { |
| 344 |
m, err := any.UnmarshalNew() |
| 345 |
if err != nil { |
| 346 |
// Ignore malformed Any values. |
| 347 |
continue |
| 348 |
} |
| 349 |
details = append(details, m) |
| 350 |
} |
| 351 |
|
| 352 |
return parseDetails(details) |
| 353 |
} |
| 354 |
|
| 355 |
// HTTPCode returns the underlying HTTP response status code. This method returns |
| 356 |
// `-1` if the underlying error is a [google.golang.org/grpc/status.Status]. To |
| 357 |
// check gRPC error codes use [google.golang.org/grpc/status.Code]. |
| 358 |
func (a *APIError) HTTPCode() int { |
| 359 |
if a.httpErr == nil { |
| 360 |
return -1 |
| 361 |
} |
| 362 |
return a.httpErr.Code |
| 363 |
} |