forked from nyaruka/goflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
70 lines (54 loc) · 1.79 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
package excellent
import (
"fmt"
"strings"
"github.com/nyaruka/goflow/utils"
"github.com/antlr/antlr4/runtime/Go/antlr"
)
// TemplateError is an error which occurs during evaluation of an expression
type TemplateError struct {
expression string
message string
}
func (e TemplateError) Error() string {
return fmt.Sprintf("error evaluating %s: %s", e.expression, e.message)
}
// TemplateErrors represents the list of all errors encountered during evaluation of a template
type TemplateErrors struct {
errors []*TemplateError
}
func NewTemplateErrors() *TemplateErrors {
return &TemplateErrors{}
}
func (e *TemplateErrors) Add(expression, message string) {
e.errors = append(e.errors, &TemplateError{expression: expression, message: message})
}
func (e *TemplateErrors) HasErrors() bool {
return len(e.errors) > 0
}
// Error returns a single string describing all the errors encountered
func (e *TemplateErrors) Error() string {
messages := make([]string, len(e.errors))
for i, err := range e.errors {
messages[i] = err.Error()
}
return strings.Join(messages, ", ")
}
type errorListener struct {
*antlr.DefaultErrorListener
expression string
errors []error
}
func NewErrorListener(expression string) *errorListener {
return &errorListener{expression: expression}
}
func (l *errorListener) Errors() []error {
return l.errors
}
func (l *errorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) {
// extract the part of the original expression where this error has occured
lines := strings.Split(l.expression, "\n")
lineOfError := lines[line-1]
contextOfError := lineOfError[column:utils.MinInt(column+10, len(lineOfError))]
l.errors = append(l.errors, fmt.Errorf("syntax error at %s", contextOfError))
}