Skip to content

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

@geoff-ziprecruiter-com

Description

@geoff-ziprecruiter-com

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

if _, err := enc.writer.Write(b); err != nil {

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())
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions