Skip to content

Commit 68b6824

Browse files
rhysdingydotnet
authored andcommitted
Add Column field to ParserError
1 parent dcff9c4 commit 68b6824

File tree

3 files changed

+25
-5
lines changed

3 files changed

+25
-5
lines changed

decode.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,13 +121,19 @@ func (p *parser) fail() {
121121
line++
122122
}
123123
}
124+
var column int
125+
if p.parser.context_mark.column != 0 {
126+
column = p.parser.context_mark.column
127+
} else if p.parser.problem_mark.column != 0 {
128+
column = p.parser.problem_mark.column
129+
}
124130
var msg string
125131
if len(p.parser.problem) > 0 {
126132
msg = p.parser.problem
127133
} else {
128134
msg = "unknown problem parsing YAML content"
129135
}
130-
fail(&ParserError{msg, line})
136+
fail(&ParserError{msg, line, column})
131137
}
132138

133139
func (p *parser) anchor(n *Node, anchor []byte) {

decode_test.go

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1145,19 +1145,32 @@ func TestDecoderErrors(t *testing.T) {
11451145
}
11461146
}
11471147

1148-
func TestParserError(t *testing.T) {
1148+
func TestParserErrorUnmarshal(t *testing.T) {
11491149
var v struct {
11501150
A, B int
11511151
}
11521152
data := "a: 1\n=\nb: 2"
11531153
err := yaml.Unmarshal([]byte(data), &v)
11541154
asErr := new(yaml.ParserError)
1155-
if !errors.As(err, &asErr) {
1156-
t.Fatalf("error returned by Unmarshal doesn't unwrap into yaml.ParserError")
1157-
}
1155+
assert.ErrorAs(t, err, &asErr)
11581156
expectedErr := &yaml.ParserError{
11591157
Message: "could not find expected ':'",
11601158
Line: 2,
1159+
Column: 0,
1160+
}
1161+
assert.DeepEqual(t, expectedErr, asErr)
1162+
}
1163+
1164+
func TestParserErrorDecoder(t *testing.T) {
1165+
var v any
1166+
data := "value: -"
1167+
err := yaml.NewDecoder(strings.NewReader(data)).Decode(&v)
1168+
asErr := new(yaml.ParserError)
1169+
assert.ErrorAs(t, err, &asErr)
1170+
expectedErr := &yaml.ParserError{
1171+
Message: "block sequence entries are not allowed in this context",
1172+
Line: 0,
1173+
Column: 7,
11611174
}
11621175
assert.DeepEqual(t, expectedErr, asErr)
11631176
}

yaml.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,7 @@ func failf(format string, args ...any) {
323323
type ParserError struct {
324324
Message string
325325
Line int
326+
Column int
326327
}
327328

328329
func (e *ParserError) Error() string {

0 commit comments

Comments
 (0)