I can't detect a json.SyntaxError while checking the error returned from a failed decoder.Decode operation!
Here you can see a working example in playground.
As you can see the debugger confirm to me it's a pointer to a json.SyntaxError, but errors.Is can't detect it.

I checked the errors.Is implementation:
func Is(err, target error) bool {
if target == nil {
return err == target
}
isComparable := reflectlite.TypeOf(target).Comparable()
for {
if isComparable && err == target {
return true
}
if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
return true
}
// TODO: consider supporting target.Is(err). This would allow
// user-definable predicates, but also may allow for coping with sloppy
// APIs, thereby making it easier to get away with them.
if err = Unwrap(err); err == nil {
return false
}
}
}
And they are comparable (isComparable variable is true) but, when I would expect it to return true when it does if isComparable && err == target { it goes on...
What am I doing wrong? Thanks in advance.
What is currently happening is that you compare the memory address of a new json.SyntaxError to the error returned from Decode. As you have noticed this will never be true.
What you want to do is a bit different: check if err is of type SyntaxError and then work with that object directly. This is possible using type assertions, which basically check if the underlying type of an interface (error in this case) is a more specific type.
This is what errors.As does. It populates a specific error type that you specify. Using this method, one lands at the following code:
if err != nil {
var serr *json.SyntaxError
if errors.As(err, &serr) {
fmt.Println("Syntax error:", serr)
fmt.Println("Offset:", serr.Offset)
} else {
fmt.Println("Other error:", err)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With