-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
81 lines (67 loc) · 1.44 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
package lr0
import (
"fmt"
"io"
"github.com/pkg/errors"
)
// NewParseError creates new Error by wrapping ErrParse
func NewParseError(msg string) error {
return &parseError{
error: errors.Wrap(ErrParse, msg),
}
}
//// NewParseErrorf creates new Error by wrapping ErrParse
//func NewParseErrorf(format string, args ...any) error {
// return &parseError{
// error: errors.Wrapf(ErrParse, format, args...),
// }
//}
type StatePrinter interface {
String() string
Format(s fmt.State, verb rune)
}
// WithSource wraps the given error to append State info to error message
func WithSource(err error, state StatePrinter) error {
return &withSource{
error: err,
src: state,
}
}
type parseError struct {
error
}
func (p *parseError) Unwrap() error { return p.error }
func (p *parseError) Format(s fmt.State, verb rune) {
if x, ok := p.error.(fmt.Formatter); ok {
x.Format(s, verb)
return
}
switch verb {
case 'v', 's', 'q':
io.WriteString(s, p.Error())
}
}
type withSource struct {
error
src StatePrinter
}
func (w *withSource) Error() string {
return w.error.Error() + " near " + fmt.Sprintf("%s", w.src)
}
func (w *withSource) Unwrap() error {
return w.error
}
func (w *withSource) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
io.WriteString(s, w.error.Error())
io.WriteString(s, " near:\n")
w.src.Format(s, verb)
return
}
fallthrough
case 's', 'q':
io.WriteString(s, w.Error())
}
}