@@ -40,6 +40,10 @@ func (e *ErrorList) Add(err Error) {
|
||||
*e = append(*e, err)
|
||||
}
|
||||
|
||||
func (e *ErrorList) AddAt(p src.Position, err error) {
|
||||
e.Add(Error{p, err})
|
||||
}
|
||||
|
||||
// addext appends an error to the list, tagged with the
|
||||
func (e *ErrorList) addext(err error) {
|
||||
e.Add(exterr(err))
|
||||
@@ -71,11 +75,11 @@ func (e ErrorList) Error() string {
|
||||
func LogError(l *log.Logger, err error, max int) {
|
||||
if list, ok := err.(ErrorList); ok {
|
||||
for i, e := range list {
|
||||
l.Printf("%s\n", e)
|
||||
if max > 0 && i == max {
|
||||
l.Print("too many errors")
|
||||
return
|
||||
}
|
||||
l.Printf("%s\n", e)
|
||||
}
|
||||
} else if err != nil {
|
||||
l.Printf("%s\n", err)
|
||||
|
||||
72
build/error_test.go
Normal file
72
build/error_test.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package build
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"testing"
|
||||
|
||||
"github.com/mmcloughlin/avo/src"
|
||||
)
|
||||
|
||||
func TestLogErrorNil(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
l := log.New(&buf, "prefix: ", 0)
|
||||
LogError(l, nil, 0)
|
||||
if buf.String() != "" {
|
||||
t.Fatalf("should print nothing for nil error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogErrorNonErrorList(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
l := log.New(&buf, "prefix: ", 0)
|
||||
err := errors.New("not an ErrorList")
|
||||
LogError(l, err, 0)
|
||||
got := buf.String()
|
||||
expect := "prefix: " + err.Error() + "\n"
|
||||
if got != expect {
|
||||
t.Fatalf("got\t%q\nexpect\t%q\n", got, expect)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogErrorList(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
l := log.New(&buf, "prefix: ", 0)
|
||||
|
||||
e := ErrorList{}
|
||||
filename := "asm.go"
|
||||
err := errors.New("some kind of error")
|
||||
n := 7
|
||||
for i := 1; i <= n; i++ {
|
||||
p := src.Position{Filename: filename, Line: i}
|
||||
e.AddAt(p, err)
|
||||
}
|
||||
|
||||
expect := ""
|
||||
// Unlimited print.
|
||||
LogError(l, e, 0)
|
||||
for i := 1; i <= n; i++ {
|
||||
expect += fmt.Sprintf("prefix: %s:%d: some kind of error\n", filename, i)
|
||||
}
|
||||
|
||||
// Max equal to number of errors.
|
||||
LogError(l, e, n)
|
||||
for i := 1; i <= n; i++ {
|
||||
expect += fmt.Sprintf("prefix: %s:%d: some kind of error\n", filename, i)
|
||||
}
|
||||
|
||||
// Max less than number of errors.
|
||||
m := n / 2
|
||||
LogError(l, e, m)
|
||||
for i := 1; i <= m; i++ {
|
||||
expect += fmt.Sprintf("prefix: %s:%d: some kind of error\n", filename, i)
|
||||
}
|
||||
expect += fmt.Sprintf("prefix: too many errors\n")
|
||||
|
||||
got := buf.String()
|
||||
if got != expect {
|
||||
t.Fatalf("got\n%s\nexpect\n%s\n", got, expect)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user