jennifer
jennifer copied to clipboard
Wrap error from go/format as it is scanner.ErrorList
Hi,
Using jen
a lot lately (great project, btw). It was difficult to debug as the error is just a string with the resulting code which can be quite hard to figure out without doing properly formatting the resulting error.
Since go/format
returns a scanner.ErrorList error type, it would be nice to be able to errors.As
to interact with the errors. This allow the code to be more like:
err := f.Render(customJenCode)
if err != nil {
var se scanner.ErrorList
if errors.As(err, &se) {
for _, e := range se {
fmt.Printf("position: %+v", e.Pos)
fmt.Println("message:", e.Msg)
}
}
t.Fatal(err)
}
Currently, I'm using my fork and this is the best I could come up with:
func jenDebug(err error) {
es := err.Error()
var se scanner.ErrorList
if errors.As(err, &se) {
for _, e := range se {
// fmt.Println("line:", e.Pos.Line)
// fmt.Println("column:", e.Pos.Column)
// fmt.Println("message:", e.Msg)
_, a, found := strings.Cut(es, e.Msg)
if found {
ss := strings.Split(a, "\n")
for i, l := range ss {
if i == e.Pos.Line {
fmt.Printf("%d: %s <---- ERROR: %s\n", i, l, e.Msg)
} else {
fmt.Printf("%d: %s\n", i, l)
}
}
// fmt.Println("after:", a)
}
}
}
}
This would help the debugging experience, not perfect by any means. Let me know what you think.
Not an expert on the matter so I would appreciate to know how others debug generated code 😄