Skip to content

Commit

Permalink
Improve error message for undefined template key (#1032)
Browse files Browse the repository at this point in the history
* Add custom error message for undefined key while rendering

* Code refactor

* Fix Lint

* Code Refactor

* Change Undefined key error message

* Update pkg/param/render.go

Co-authored-by: Vivek Singh <vsingh.ggits.2010@gmail.com>

* Update error message

* Use sprintf

* Minor fix

* Fix gofmt issues

* Update pkg/param/render.go

Co-authored-by: Pavan Navarathna <pavan@kasten.io>

Co-authored-by: Vivek Singh <vsingh.ggits.2010@gmail.com>
Co-authored-by: Pavan Navarathna <pavan@kasten.io>
  • Loading branch information
3 people committed Jul 2, 2021
1 parent aaa330e commit 7741188
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions pkg/param/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ package param

import (
"bytes"
"fmt"
"reflect"
"strings"
"text/template"

"github.com/Masterminds/sprig"
Expand All @@ -25,6 +27,10 @@ import (
crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1"
)

const (
undefinedKeyErrorMsg = "map has no entry for key "
)

// RenderArgs function renders the arguments required for execution
func RenderArgs(args map[string]interface{}, tp TemplateParams) (map[string]interface{}, error) {
ram := make(map[string]interface{}, len(args))
Expand Down Expand Up @@ -119,11 +125,24 @@ func renderStringArg(arg string, tp TemplateParams) (string, error) {
}
buf := bytes.NewBuffer(nil)
if err = t.Execute(buf, tp); err != nil {
// Check if Error is because of undefined key,
// which will lead on execute error on first undefined (missingkey=error).
// Get the undefined key name from the error message.
if strings.Contains(err.Error(), undefinedKeyErrorMsg) {
return "", newUndefinedKeyError(err.Error())
}
return "", errors.WithStack(err)
}
return buf.String(), nil
}

func newUndefinedKeyError(err string) error {
pos := strings.LastIndex(err, undefinedKeyErrorMsg)
adjustedPos := pos + len(undefinedKeyErrorMsg)
key := strings.Trim(err[adjustedPos:], "\"")
return errors.WithStack(errors.New(fmt.Sprintf("Failed to render template: \"%s\" not found", key)))
}

// RenderObjectRefs function renders object refs from TemplateParams
func RenderObjectRefs(in map[string]crv1alpha1.ObjectReference, tp TemplateParams) (map[string]crv1alpha1.ObjectReference, error) {
out := make(map[string]crv1alpha1.ObjectReference, len(in))
Expand Down

0 comments on commit 7741188

Please sign in to comment.