make sure parse error includes offending text (#7561)

This commit is contained in:
Steven Soroka 2020-05-27 14:58:58 -04:00 committed by GitHub
parent 7b06624885
commit a438678d5b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 3 deletions

View File

@ -38,7 +38,20 @@ func (e *ParseError) Error() string {
buffer = buffer[:eol] buffer = buffer[:eol]
} }
if len(buffer) > maxErrorBufferSize { if len(buffer) > maxErrorBufferSize {
buffer = buffer[:maxErrorBufferSize] + "..." startEllipsis := true
offset := e.Offset - e.LineOffset
start := offset - maxErrorBufferSize
if start < 0 {
startEllipsis = false
start = 0
}
// if we trimmed it the column won't line up. it'll always be the last character,
// because the parser doesn't continue past it, but point it out anyway so
// it's obvious where the issue is.
buffer = buffer[start:offset] + "<-- here"
if startEllipsis {
buffer = "..." + buffer
}
} }
return fmt.Sprintf("metric parse error: %s at %d:%d: %q", e.msg, e.LineNumber, e.Column, buffer) return fmt.Sprintf("metric parse error: %s at %d:%d: %q", e.msg, e.LineNumber, e.Column, buffer)
} }

View File

@ -790,7 +790,7 @@ func TestParserErrorString(t *testing.T) {
{ {
name: "buffer too long", name: "buffer too long",
input: []byte("cpu " + strings.Repeat("ab", maxErrorBufferSize) + "=invalid\ncpu value=42"), input: []byte("cpu " + strings.Repeat("ab", maxErrorBufferSize) + "=invalid\ncpu value=42"),
errString: "metric parse error: expected field at 1:2054: \"cpu " + strings.Repeat("ab", maxErrorBufferSize)[:maxErrorBufferSize-4] + "...\"", errString: "metric parse error: expected field at 1:2054: \"...b" + strings.Repeat("ab", maxErrorBufferSize/2-1) + "=<-- here\"",
}, },
{ {
name: "multiple line error", name: "multiple line error",
@ -834,7 +834,7 @@ func TestStreamParserErrorString(t *testing.T) {
name: "buffer too long", name: "buffer too long",
input: []byte("cpu " + strings.Repeat("ab", maxErrorBufferSize) + "=invalid\ncpu value=42"), input: []byte("cpu " + strings.Repeat("ab", maxErrorBufferSize) + "=invalid\ncpu value=42"),
errs: []string{ errs: []string{
"metric parse error: expected field at 1:2054: \"cpu " + strings.Repeat("ab", maxErrorBufferSize)[:maxErrorBufferSize-4] + "...\"", "metric parse error: expected field at 1:2054: \"...b" + strings.Repeat("ab", maxErrorBufferSize/2-1) + "=<-- here\"",
}, },
}, },
{ {