From d96284f2e2634a6bdfced8c39f26094f56720051 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Tue, 28 Aug 2018 17:11:36 -0700 Subject: [PATCH] tfdiags: FormatErrorPrefixed When presenting an error that may be a PathError, the error's path is usually relative to some other value. If the caller is able to express that value (or, more often, a reference to it) in HCL syntax then this method will produce a complete expression in the error message, concatenating any path information from the error to the end of the given prefix string. --- tfdiags/config_traversals.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tfdiags/config_traversals.go b/tfdiags/config_traversals.go index 1b6b2441d9..8e41f46ed2 100644 --- a/tfdiags/config_traversals.go +++ b/tfdiags/config_traversals.go @@ -54,3 +54,15 @@ func FormatError(err error) string { return fmt.Sprintf("%s: %s", FormatCtyPath(perr.Path), perr.Error()) } + +// FormatErrorPrefixed is like FormatError except that it presents any path +// information after the given prefix string, which is assumed to contain +// an HCL syntax representation of the value that errors are relative to. +func FormatErrorPrefixed(err error, prefix string) string { + perr, ok := err.(cty.PathError) + if !ok || len(perr.Path) == 0 { + return fmt.Sprintf("%s: %s", prefix, err.Error()) + } + + return fmt.Sprintf("%s%s: %s", prefix, FormatCtyPath(perr.Path), perr.Error()) +}