...

Source file src/sigs.k8s.io/cli-utils/pkg/object/validation/error.go

Documentation: sigs.k8s.io/cli-utils/pkg/object/validation

     1  // Copyright 2022 The Kubernetes Authors.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package validation
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  
    10  	"sigs.k8s.io/cli-utils/pkg/object"
    11  )
    12  
    13  func NewError(cause error, ids ...object.ObjMetadata) *Error {
    14  	return &Error{
    15  		ids:   object.ObjMetadataSet(ids),
    16  		cause: cause,
    17  	}
    18  }
    19  
    20  // Error wraps an error with the object or objects it applies to.
    21  type Error struct {
    22  	ids   object.ObjMetadataSet
    23  	cause error
    24  }
    25  
    26  // Identifiers returns zero or more object IDs which are invalid.
    27  func (ve *Error) Identifiers() object.ObjMetadataSet {
    28  	return ve.ids
    29  }
    30  
    31  // Unwrap returns the cause of the error.
    32  // This may be useful when printing the cause without printing the identifiers.
    33  func (ve *Error) Unwrap() error {
    34  	return ve.cause
    35  }
    36  
    37  // Error stringifies the the error.
    38  func (ve *Error) Error() string {
    39  	switch {
    40  	case len(ve.ids) == 0:
    41  		return fmt.Sprintf("validation error: %v", ve.cause.Error())
    42  	case len(ve.ids) == 1:
    43  		return fmt.Sprintf("invalid object: %q: %v", ve.ids[0], ve.cause.Error())
    44  	default:
    45  		var b strings.Builder
    46  		_, _ = fmt.Fprintf(&b, "invalid objects: [%q", ve.ids[0])
    47  		for _, id := range ve.ids[1:] {
    48  			_, _ = fmt.Fprintf(&b, ", %q", id)
    49  		}
    50  		_, _ = fmt.Fprintf(&b, "] %v", ve.cause)
    51  		return b.String()
    52  	}
    53  }
    54  

View as plain text