Skip to content

Commit b3ef90e

Browse files
caarlos0odeke-em
authored andcommitted
encoding/json: implement Is on SyntaxError
Allows users to check: errors.Is(err, &json.SyntaxError{}) which is the recommended way of checking for kinds of errors. Change-Id: I20dc805f20212765e9936a82d9cb7822e73ec4ef GitHub-Last-Rev: e2627cc GitHub-Pull-Request: #41210 Reviewed-on: https://go-review.googlesource.com/c/go/+/253037 Reviewed-by: Emmanuel Odeke <[email protected]> Run-TryBot: Emmanuel Odeke <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent 92b2b88 commit b3ef90e

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

src/encoding/json/scanner.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,12 @@ type SyntaxError struct {
4949

5050
func (e *SyntaxError) Error() string { return e.msg }
5151

52+
// Is returns true if target is a SyntaxError.
53+
func (e *SyntaxError) Is(target error) bool {
54+
_, ok := target.(*SyntaxError)
55+
return ok
56+
}
57+
5258
// A scanner is a JSON scanning state machine.
5359
// Callers call scan.reset and then pass bytes in one at a time
5460
// by calling scan.step(&scan, c) for each byte.

src/encoding/json/scanner_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ package json
66

77
import (
88
"bytes"
9+
"errors"
10+
"fmt"
911
"math"
1012
"math/rand"
1113
"reflect"
@@ -201,6 +203,13 @@ func TestIndentErrors(t *testing.T) {
201203
}
202204
}
203205

206+
func TestSyntaxErrorIs(t *testing.T) {
207+
err := fmt.Errorf("apackage: %w: failed to parse struct", &SyntaxError{"some error", 43})
208+
if !errors.Is(err, &SyntaxError{}) {
209+
t.Fatalf("%v should be unwrapped to a SyntaxError", err)
210+
}
211+
}
212+
204213
func diff(t *testing.T, a, b []byte) {
205214
for i := 0; ; i++ {
206215
if i >= len(a) || i >= len(b) || a[i] != b[i] {

0 commit comments

Comments
 (0)