...

Source file src/edge-infra.dev/pkg/edge/api/apierror/gcp/gcperror.go

Documentation: edge-infra.dev/pkg/edge/api/apierror/gcp

     1  package gcp
     2  
     3  import (
     4  	"errors"
     5  
     6  	"google.golang.org/api/googleapi"
     7  	"google.golang.org/grpc/codes"
     8  	"google.golang.org/grpc/status"
     9  )
    10  
    11  type Error struct {
    12  	Err     error
    13  	Message string
    14  	Code    int
    15  	Verbose string
    16  	Host    string
    17  }
    18  
    19  // Wrap creates a GCPError
    20  func Wrap(err error) *Error {
    21  	if err == nil {
    22  		return nil
    23  	}
    24  	if e, ok := err.(*googleapi.Error); ok {
    25  		return &Error{
    26  			Err:     e,
    27  			Message: e.Message,
    28  			Code:    e.Code,
    29  			Verbose: e.Error(),
    30  			Host:    e.Header.Get("Host"),
    31  		}
    32  	}
    33  	// wraps grpc errors such as those used in secret manager client
    34  	if e, ok := status.FromError(err); ok {
    35  		return &Error{
    36  			Err:     e.Err(),
    37  			Message: e.Message(),
    38  			Code:    int(e.Code()),
    39  		}
    40  	}
    41  	return &Error{
    42  		Err:     err,
    43  		Message: err.Error(),
    44  	}
    45  }
    46  
    47  func New(msg string) *Error {
    48  	return Wrap(errors.New(msg))
    49  }
    50  
    51  // Error implements the error interface.
    52  func (g *Error) Error() string {
    53  	return g.Message
    54  }
    55  
    56  // Unwrap retrieves the original error.
    57  func (g *Error) Unwrap() error { return g.Err }
    58  
    59  // Extensions additional data about gcp error
    60  func (g *Error) Extensions() map[string]interface{} {
    61  	return map[string]interface{}{
    62  		"statusCode": g.Code,
    63  		//"verbose":    g.Verbose, We don't want to expose implementation details
    64  		"host": g.Host,
    65  	}
    66  }
    67  
    68  // IgnoreNotFound returns nil if the error is an Error
    69  // with Code=404, otherwise it returns the provided error
    70  func IgnoreNotFound(err error) error {
    71  	var gcpErr *Error
    72  	if !errors.As(err, &gcpErr) {
    73  		return err
    74  	}
    75  	if gcpErr.Code == int(codes.NotFound) {
    76  		return nil
    77  	}
    78  	return err
    79  }
    80  

View as plain text