segmentio / encoding

Go package containing implementations of efficient encoding, decoding, and validation APIs.
MIT License
987 stars 52 forks source link

json.Encoder.Encode does not return error from underlying writer #139

Open geoff-ziprecruiter-com opened 3 months ago

geoff-ziprecruiter-com commented 3 months ago

If the writer encounters an error the error is stored in the encoder, but it is not returned.

https://github.com/segmentio/encoding/blob/3055897c1c5b74bc4c4ec5f702c22ed90020f410/json/json.go#L537

This is because the above line is creating a new err variable due to the : in the assignment.

This test code demonstrates the issue:

type errWriter struct{}

func (ew *errWriter) Write([]byte) (n int, err error) {
    return 0, errors.New("test-error")
}

func TestWriterErr(t *testing.T) {
    t.Parallel()

    enc := NewEncoder(&errWriter{})

    err := enc.Encode("")

    if err == nil {
        t.Error("expected error not returned")
    } else if err.Error() != "test-error" {
        t.Errorf("unexpected error returned: want=test-error got=%s", err.Error())
    }
}