#Errors interface compatibility

20 messages · Page 1 of 1 (latest)

frail portal
#

I created a variable in Go:

go

var UnexpectedEOFJSON = errors.New("unexpected end of JSON input")

This variable is intended to handle situations where a JSON input unexpectedly terminates. In my implementation, I retrieve a column that has the potential to be null. Consequently, when I attempt to unmarshal the JSON into the appropriate struct, I encounter an issue: if the []byte is empty, the unmarshalling process may trigger an "unexpected end of JSON input" error.

To address this, I introduced a conditional check:

if errors.Is(err, UnexpectedEOFJSON) {
// handle the error
}

However, this check consistently returns false, even though, when I output the error message, it explicitly states "unexpected end of JSON input". This discrepancy indicates that the error handling is not functioning as expected, and the condition designed to catch this specific error is not being met.

mortal thunder
#

probably doing fmt.Errorf("something something %s") instead of fmt.Errorf("something something %w") ?

#

else try printing fmt.Printf("%#+v %T\n", err, err) when doing the check, it will tell you what is actually your error

frail portal
#

Nope i just did return fmt.Errorf("%w", err)

#

Ok i will try

frail portal
#

@mortal thunder &json.SyntaxError{msg:"unexpected end of JSON input", Offset:0} *json.SyntaxError
so it wont work ?

mortal thunder
#

you are using a pointer

#

so it does pointers as identity and you have multiple instances of the pointer so they don't match

#

by default use values for everything unless you have a reason to use pointers (ie, you want shared state)

frail portal
#

i've to use pointer because

var ErrCustomError = errors.New("unexpected end of JSON input")

func main() {
    var b []byte
    var qu LO
    if err := json.Unmarshal(b, qu); err != nil {
        if errors.Is(err, ErrCustomError) {
            fmt.Println("ok")
        }
    }
}
#

when i don't &qu

#

"call of Unmarshal passes non-pointer as second argument" as error

#

it is a reproduction

mortal thunder
#

I don't understand

#

which line of code produce this

frail portal
#

i'll just compare the string it's easier,
you said that i'm using pointer but with unmarshall if you do not unse &qu it will complain.

mortal thunder
#

qu is not the error

#

you need a pointer to qu because it's an out parameter

#

you don't want a pointer on the error because it needs to compare types

#

you can also implement a custom Is method on your error type