github.com/hashicorp/packer@v1.14.3/internal/hcp/api/errors.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package api 5 6 import ( 7 "fmt" 8 "regexp" 9 "strconv" 10 11 "google.golang.org/grpc/codes" 12 ) 13 14 const ( 15 _ = iota 16 InvalidClientConfig 17 ) 18 19 // ClientError represents a generic error for the Cloud Packer Service client. 20 type ClientError struct { 21 StatusCode uint 22 Err error 23 } 24 25 // Error returns the string message for some ClientError. 26 func (c *ClientError) Error() string { 27 return fmt.Sprintf("status %d: err %v", c.StatusCode, c.Err) 28 } 29 30 var errCodeRegex = regexp.MustCompilePOSIX(`[Cc]ode"?:([0-9]+)`) 31 32 // CheckErrorCode checks the error string for err for some code and returns true 33 // if the code is found. Ideally this function should use status.FromError 34 // https://pkg.go.dev/google.golang.org/grpc/status#pkg-functions but that 35 // doesn't appear to work for all of the Cloud Packer Service response errors. 36 func CheckErrorCode(err error, code codes.Code) bool { 37 if err == nil { 38 return false 39 } 40 41 // If the error string doesn't match the code we're looking for, we 42 // can ignore it and return false immediately. 43 matches := errCodeRegex.FindStringSubmatch(err.Error()) 44 if len(matches) == 0 { 45 return false 46 } 47 48 // Safe to ignore the error here since the regex's submatch is always a 49 // valid integer given the format ([0-9]+) 50 errCode, _ := strconv.Atoi(matches[1]) 51 return errCode == int(code) 52 }