aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/zclconf/go-cty/cty/error.go
blob: dd139f724994d9f57e7c46476dc7e5d4ccdd8008 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package cty

import (
	"fmt"
)

// PathError is a specialization of error that represents where in a
// potentially-deep data structure an error occured, using a Path.
type PathError struct {
	error
	Path Path
}

func errorf(path Path, f string, args ...interface{}) error {
	// We need to copy the Path because often our caller builds it by
	// continually mutating the same underlying buffer.
	sPath := make(Path, len(path))
	copy(sPath, path)
	return PathError{
		error: fmt.Errorf(f, args...),
		Path:  sPath,
	}
}

// NewErrorf creates a new PathError for the current path by passing the
// given format and arguments to fmt.Errorf and then wrapping the result
// similarly to NewError.
func (p Path) NewErrorf(f string, args ...interface{}) error {
	return errorf(p, f, args...)
}

// NewError creates a new PathError for the current path, wrapping the given
// error.
func (p Path) NewError(err error) error {
	// if we're being asked to wrap an existing PathError then our new
	// PathError will be the concatenation of the two paths, ensuring
	// that we still get a single flat PathError that's thus easier for
	// callers to deal with.
	perr, wrappingPath := err.(PathError)
	pathLen := len(p)
	if wrappingPath {
		pathLen = pathLen + len(perr.Path)
	}

	sPath := make(Path, pathLen)
	copy(sPath, p)
	if wrappingPath {
		copy(sPath[len(p):], perr.Path)
	}

	return PathError{
		error: err,
		Path:  sPath,
	}
}