aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/onsi/gomega/gstruct/errors/nested_types.go
blob: 188492b212f9d53ad08944f4a49ad7f6384272f1 (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package errors

import (
	"fmt"
	"strings"

	"github.com/onsi/gomega/types"
)

// A stateful matcher that nests other matchers within it and preserves the error types of the
// nested matcher failures.
type NestingMatcher interface {
	types.GomegaMatcher

	// Returns the failures of nested matchers.
	Failures() []error
}

// An error type for labeling errors on deeply nested matchers.
type NestedError struct {
	Path string
	Err  error
}

func (e *NestedError) Error() string {
	// Indent Errors.
	indented := strings.Replace(e.Err.Error(), "\n", "\n\t", -1)
	return fmt.Sprintf("%s:\n\t%v", e.Path, indented)
}

// Create a NestedError with the given path.
// If err is a NestedError, prepend the path to it.
// If err is an AggregateError, recursively Nest each error.
func Nest(path string, err error) error {
	if ag, ok := err.(AggregateError); ok {
		var errs AggregateError
		for _, e := range ag {
			errs = append(errs, Nest(path, e))
		}
		return errs
	}
	if ne, ok := err.(*NestedError); ok {
		return &NestedError{
			Path: path + ne.Path,
			Err:  ne.Err,
		}
	}
	return &NestedError{
		Path: path,
		Err:  err,
	}
}

// An error type for treating multiple errors as a single error.
type AggregateError []error

// Error is part of the error interface.
func (err AggregateError) Error() string {
	if len(err) == 0 {
		// This should never happen, really.
		return ""
	}
	if len(err) == 1 {
		return err[0].Error()
	}
	result := fmt.Sprintf("[%s", err[0].Error())
	for i := 1; i < len(err); i++ {
		result += fmt.Sprintf(", %s", err[i].Error())
	}
	result += "]"
	return result
}