| 1 |
package server |
| 2 |
|
| 3 |
import "strings" |
| 4 |
|
| 5 |
var fatalError = "fatal: invalid GroupedError" |
| 6 |
|
| 7 |
// GroupedError collects related errors and exposes them as a single error. |
| 8 |
// Users can inspect the `Errors` field for details on the suberrors. |
| 9 |
type GroupedError struct { |
| 10 |
// The prefix string returned by `Error()`, followed by the grouped errors. |
| 11 |
Prefix string |
| 12 |
Errors []error |
| 13 |
} |
| 14 |
|
| 15 |
func (gErr *GroupedError) Error() string { |
| 16 |
if len(gErr.Errors) == 0 { |
| 17 |
return fatalError |
| 18 |
} |
| 19 |
var sb strings.Builder |
| 20 |
for _, err := range gErr.Errors { |
| 21 |
sb.WriteString("\n") |
| 22 |
sb.WriteString(err.Error()) |
| 23 |
} |
| 24 |
return gErr.Prefix + sb.String() |
| 25 |
} |
| 26 |
|
| 27 |
func createGroupedError(prefix string, errors []error) error { |
| 28 |
if len(errors) == 0 { |
| 29 |
return nil |
| 30 |
} |
| 31 |
return &GroupedError{Prefix: prefix, Errors: errors} |
| 32 |
} |
| 33 |
|
| 34 |
func (gErr *GroupedError) containsSubstring(substr string) bool { |
| 35 |
for _, err := range gErr.Errors { |
| 36 |
if strings.Contains(err.Error(), substr) { |
| 37 |
return true |
| 38 |
} |
| 39 |
} |
| 40 |
return false |
| 41 |
} |
| 42 |
|
| 43 |
// containsKnownSubstrings is used to match a set of known errors. |
| 44 |
// Each substring must only match error in the GroupedError. |
| 45 |
// In other words, there must not be overlap in the substring matches. |
| 46 |
func (gErr *GroupedError) containsKnownSubstrings(substrs []string) bool { |
| 47 |
if len(gErr.Errors) != len(substrs) { |
| 48 |
return false |
| 49 |
} |
| 50 |
matchedGErr := make(map[string]bool) |
| 51 |
for _, err := range gErr.Errors { |
| 52 |
matchedGErr[err.Error()] = false |
| 53 |
for _, substr := range substrs { |
| 54 |
if strings.Contains(err.Error(), substr) { |
| 55 |
if matchedGErr[err.Error()] { |
| 56 |
// Duplicated match for the error. |
| 57 |
return false |
| 58 |
} |
| 59 |
matchedGErr[err.Error()] = true |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
for _, matched := range matchedGErr { |
| 65 |
if !matched { |
| 66 |
return false |
| 67 |
} |
| 68 |
} |
| 69 |
return true |
| 70 |
} |
| 71 |
|
| 72 |
func (gErr *GroupedError) containsOnlySubstring(substr string) bool { |
| 73 |
if len(gErr.Errors) != 1 { |
| 74 |
return false |
| 75 |
} |
| 76 |
return gErr.containsSubstring(substr) |
| 77 |
} |