Skip to content

Commit

Permalink
feat: structured errors (#12)
Browse files Browse the repository at this point in the history
* validate returning ValidationError

Signed-off-by: Alfredo Garo <[email protected]>

* PR feedback

Signed-off-by: Alfredo Garo <[email protected]>
  • Loading branch information
garomonegro authored Jan 25, 2022
1 parent 167c7a3 commit fd9c0f3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
14 changes: 14 additions & 0 deletions pkg/client/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ limitations under the License.
package client

import (
"encoding/json"
"fmt"
"io/fs"
"io/ioutil"
"os"
Expand All @@ -22,6 +24,7 @@ import (
"github.com/keikoproj/cluster-validator/pkg/api/v1alpha1"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
)

Expand Down Expand Up @@ -64,6 +67,7 @@ func NewFieldValidationResult(path string) FieldValidationResult {
}

type ValidationSummary struct {
GVR schema.GroupVersionResource
FieldValidation []FieldValidationResult
ConditionValidation []ConditionValidationResult
}
Expand Down Expand Up @@ -107,3 +111,13 @@ func NewValidator(c dynamic.Interface, m *v1alpha1.ClusterValidation) *Validator

return v
}

type ValidationError struct {
Message error
Summary ValidationSummary
}

func (e *ValidationError) Error() string {
prettySummary, _ := json.MarshalIndent(e.Summary, "", "\t")
return fmt.Sprintf("%v. \n%s", e.Message, string(prettySummary))
}
8 changes: 6 additions & 2 deletions pkg/client/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,10 @@ func (v *Validator) Validate() error {
prettyPrintStruct(summary)
}
if r.Required {
v.Waiter.errors <- errors.Errorf("failure threshold met for resource '%v'", resourceName)
v.Waiter.errors <- &ValidationError{
Message: errors.Errorf("failure threshold met for resource '%v'", resourceName),
Summary: summary,
}
}
log.Warnf("%v resource '%v' validation failed", failEmoji, resourceName)
return
Expand All @@ -107,7 +110,7 @@ func (v *Validator) Validate() error {
case <-v.Waiter.finished:
finished = true
case err := <-v.Waiter.errors:
return errors.Wrap(err, "resource validation failed")
return err
}
}

Expand Down Expand Up @@ -163,6 +166,7 @@ func (v *Validator) validateResources(r v1alpha1.ClusterResource, resources []un
}

if failed {
summary.GVR = groupVersionResource(r.APIVersion, r.Name)
return summary, errors.New("failed to validate resources")
}

Expand Down

0 comments on commit fd9c0f3

Please sign in to comment.