2025-11-30 13:32:15 -05:00
|
|
|
// Copyright IBM Corp. 2013, 2025
|
2023-08-10 18:53:29 -04:00
|
|
|
// SPDX-License-Identifier: BUSL-1.1
|
2023-03-02 15:37:05 -05:00
|
|
|
|
2022-11-07 14:16:04 -05:00
|
|
|
package api
|
2021-08-05 09:25:19 -04:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
2025-01-21 13:18:17 -05:00
|
|
|
"regexp"
|
|
|
|
|
"strconv"
|
2021-08-05 09:25:19 -04:00
|
|
|
|
|
|
|
|
"google.golang.org/grpc/codes"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
_ = iota
|
|
|
|
|
InvalidClientConfig
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// ClientError represents a generic error for the Cloud Packer Service client.
|
|
|
|
|
type ClientError struct {
|
|
|
|
|
StatusCode uint
|
|
|
|
|
Err error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Error returns the string message for some ClientError.
|
|
|
|
|
func (c *ClientError) Error() string {
|
|
|
|
|
return fmt.Sprintf("status %d: err %v", c.StatusCode, c.Err)
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-21 13:18:17 -05:00
|
|
|
var errCodeRegex = regexp.MustCompilePOSIX(`[Cc]ode"?:([0-9]+)`)
|
|
|
|
|
|
2022-11-07 14:16:04 -05:00
|
|
|
// CheckErrorCode checks the error string for err for some code and returns true
|
2021-12-01 09:58:33 -05:00
|
|
|
// if the code is found. Ideally this function should use status.FromError
|
|
|
|
|
// https://pkg.go.dev/google.golang.org/grpc/status#pkg-functions but that
|
|
|
|
|
// doesn't appear to work for all of the Cloud Packer Service response errors.
|
2022-11-07 14:16:04 -05:00
|
|
|
func CheckErrorCode(err error, code codes.Code) bool {
|
2021-08-05 09:25:19 -04:00
|
|
|
if err == nil {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-21 13:18:17 -05:00
|
|
|
// If the error string doesn't match the code we're looking for, we
|
|
|
|
|
// can ignore it and return false immediately.
|
|
|
|
|
matches := errCodeRegex.FindStringSubmatch(err.Error())
|
|
|
|
|
if len(matches) == 0 {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Safe to ignore the error here since the regex's submatch is always a
|
|
|
|
|
// valid integer given the format ([0-9]+)
|
|
|
|
|
errCode, _ := strconv.Atoi(matches[1])
|
|
|
|
|
return errCode == int(code)
|
2021-08-05 09:25:19 -04:00
|
|
|
}
|