Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect json.SyntaxError with errors.Is

Tags:

go

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.

enter image description here

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.

like image 564
Cirelli94 Avatar asked Jul 23 '26 01:07

Cirelli94


1 Answers

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)
    }
}
like image 141
xarantolus Avatar answered Jul 24 '26 23:07

xarantolus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!