This repository has been archived by the owner on Oct 11, 2019. It is now read-only.
/
errors.go
110 lines (87 loc) · 2.03 KB
/
errors.go
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package util
import (
"fmt"
)
type recoverableError interface {
canRecover() bool
}
func CanRecover(errorList ...error) bool {
for _, err := range errorList {
r, ok := err.(recoverableError)
if !ok || !r.canRecover() {
return false
}
}
return true
}
type ErrInvalidVariableName struct {
varName string
}
func NewErrInvalidVariableName(varName string) *ErrInvalidVariableName {
return &ErrInvalidVariableName{
varName: varName,
}
}
func (e *ErrInvalidVariableName) Error() string {
return fmt.Sprintf("invalid variable name: %s", e.varName)
}
func (e *ErrInvalidVariableName) canRecover() bool {
return true
}
type ErrVariableNotFound struct {
varName string
Similar string
}
func NewErrVariableNotFound(varName string, similar string) *ErrVariableNotFound {
return &ErrVariableNotFound{
varName: varName,
Similar: similar,
}
}
func (e *ErrVariableNotFound) Error() string {
if e.Similar == "" {
return fmt.Sprintf("variable not defined: %q", e.varName)
}
return fmt.Sprintf("variable not defined: %q, did you mean %q", e.varName, e.Similar)
}
func (e *ErrVariableNotFound) canRecover() bool {
return true
}
type ErrorList struct {
ErrorList []error
}
func NewErrorList(initialErrList ...error) *ErrorList {
errorList := append([]error{}, initialErrList...)
return &ErrorList{
ErrorList: errorList,
}
}
func (e *ErrorList) Add(err ...error) {
for _, currErr := range err {
switch errList := currErr.(type) {
case *ErrorList:
e.AddErrorList(errList)
default:
e.ErrorList = append(e.ErrorList, currErr)
}
}
}
func (e *ErrorList) AddErrorList(errorList *ErrorList) {
e.ErrorList = append(e.ErrorList, errorList.ErrorList...)
}
func (e *ErrorList) Error() string {
if len(e.ErrorList) == 0 {
return ""
}
result := e.ErrorList[0].Error()
for i := 1; i < len(e.ErrorList); i++ {
result += fmt.Sprintf(", %s", e.ErrorList[i].Error())
}
return result
}
func (e *ErrorList) CanRecover() bool {
return CanRecover(e.ErrorList...)
}
func (e *ErrorList) HasErrors() bool {
return len(e.ErrorList) > 0
}