Skip to content

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

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions