Hello @user5976738 and all.
I have a different solution for that problem which does not require a template function at all and it uses the text/template/parse package.
This workaround may be very useful for some of you. Example of usage:
if missingKeys, ok := IsMissingKeys(err); ok{
for _, key := range missingKeys{ println(key) }
}
Source Code:
package main
import (
"fmt"
"os"
"strings"
"strconv"
"text/template"
templateparse "text/template/parse"
)
type errMissingKeys struct {
Keys []string
TemplateName string
}
func (err errMissingKeys) Error() string {
return fmt.Sprintf("template: %s: map has no entry for keys: %s", err.TemplateName, strings.Join(err.Keys, ", "))
}
// IsMissingKeys reports whether an "err" is caused by template missing keys.
//
// Usage:
// if missingKeys, ok := IsMissingKeys(err); ok{
// for _, key := range missingKeys{ println(key) }
// }
func IsMissingKeys(err error) ([]string, bool) {
if err != nil {
if v, ok := err.(errMissingKeys); ok {
return v.Keys, true
}
}
return nil, false
}
func main() {
data := map[string]interface{}{
"bar": 34,
}
tmpl, err := template.New("myTemplate").Option("missingkey=error").Parse(`{{.baz}} {{.other}}`)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
err = tmpl.Execute(os.Stdout, data)
if err != nil {
if strings.Contains(err.Error(), "map has no entry for key ") {
// Check if a field is not a "data" match,
// which will lead on execute error on first undefined (missingkey=error).
// So collect all these keys so we can have a typed error with all unknown keys listed.
var missingKeys []string
for _, n := range tmpl.Root.Nodes {
if n.Type() == templateparse.NodeAction {
key := strings.TrimFunc(n.String(), func(r rune) bool {
return r == '{' || r == '}' || r == ' ' || r == '.'
})
if key == "" {
continue
}
if _, ok := data[key]; !ok {
missingKeys = append(missingKeys, strconv.Quote(key))
}
}
}
// if just one then keep the original error which contains the full context,
// else set to custom error type which will keep the missing keys for caller's further use.
if len(missingKeys) > 1 {
err = errMissingKeys{TemplateName: tmpl.Name(), Keys: missingKeys}
}
}
fmt.Println(err.Error())
os.Exit(1)
}
}
Playground link: https://play.golang.org/p/JMwBpU2KyP2
Best Regards, Gerasimos Maropoulos - Creator of https://iris-go.com