Skip to content

fix: keep encoder output valid when a value fails to encode - #10

Merged
ssgreg merged 1 commit into
mainfrom
fix/encoder-errors
Dec 2, 2026
Merged

ssgreg merged 1 commit into
mainfrom
fix/encoder-errors

Conversation

@ssgreg

@ssgreg ssgreg commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Any with a value encoding/json cannot marshal writes the key and no value:

logger.Info(ctx, "any", logf.Any("ch", make(chan int)), logf.Int("n", 1))
// {"level":"info","msg":"any","ch":"n":1}

The text encoder writes ch=n=1. An ArrayEncoder that calls EncodeTypeAny twice gets [{"x":1}"y"], since EncodeTypeAny never writes a separator. Errors returned by EncodeLogfObject and EncodeLogfArray are dropped.

Change

Errors follow zap's convention: a string field named after the key with an Error suffix.

  • An Any field whose value fails to marshal is replaced by that field: {"msg":"any","chError":"json: unsupported type: chan int","n":1}. The key itself is not written, so a field never holds a value of an unexpected type, which a log index with typed mappings would reject.
  • An error from an Object or Array callback is added next to whatever the callback wrote: "o":{"n":1},"oError":"boom". An inline object uses the key Error, as zap.Inline does.
  • An Any element of an array has no key, so a failing one is written as a string with the error: [{"x":1},"y","<logf: json: unsupported type: chan int>"]. An object or array written as an element of another array has no key either, and its error is still dropped; the ObjectEncoder and ArrayEncoder docs say so.
  • EncodeTypeAny writes a separator like every other EncodeType* method.

Not changed: Error(nil) still writes "<nil>", and Encode still returns an error that the built-in encoders never set. Both are API questions.

The two data races this PR used to fix, in the text encoder's JSON helper and in the default error encoder, moved to #16.

Testing

New tests in encodererrors_test.go fail on main and pass here:

  • TestJSONEncoderEncodeErrors: unsupported Any as the first field, the last field and inside a Group, Any elements in an array, failing Object, inline Object and Array. Checks the exact line and json.Valid.
  • TestTextEncoderEncodeErrors: the same cases through the text encoder.
  • TestEncodeErrorsAnyInBag: an unsupported Any in a logger Bag, encoded three times by each encoder, so the cached fragment is checked too.

go test -race ./... and golangci-lint run (v2, repo config) pass, on this branch alone and merged with #16.

Benchmarks: main and this branch built once, ten interleaved rounds, compared with benchstat. The machine was loaded during the run, so the spread is wide. New benchmarks in encodererrors_bench_test.go encode an Object, an Array, an Any struct and an Error. Only TextEncodeNested moved, by -2.5%, and B/op and allocs/op are unchanged in every row:

                         │    main     │      encoder-errors         │
                         │   sec/op    │   sec/op     vs base        │
JSONEncodeNested-15        209.0n ± 4%   210.9n ± 3%   ~     (p=0.579)
TextEncodeNested-15        209.2n ± 3%   203.9n ± 1%  -2.51% (p=0.027)
JSONEncodeCachedBag-15     82.46n ± 5%   80.46n ± 5%   ~     (p=0.315)
TextEncodeCachedBag-15     68.17n ± 3%   67.59n ± 3%   ~     (p=0.436)
Logf_ErrorField-15         55.43n ±25%   56.52n ±16%   ~     (p=0.985)
Logf_SixHeavy-15           228.3n ±23%   221.2n ±23%   ~     (p=0.971)

@ssgreg
ssgreg force-pushed the fix/encoder-errors branch from 4f8f3dd to d0daf49 Compare December 2, 2026 12:20
@ssgreg

ssgreg commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Force-pushed 4f8f3dd -> d0daf49: rebased on main and split. The two data races (the text encoder's shared JSON helper and the default error encoder) moved to #16; this PR now only covers values and callbacks that fail to encode. The code of both PRs together is the same as before.

An Any value that encoding/json cannot marshal left its key with no value, which produced invalid JSON and broken text lines, and errors returned by Object and Array callbacks were dropped. Such a field is now replaced by a key+"Error" string field holding the error, as zap does, an Object or Array callback error is added as a key+"Error" field next to what the callback wrote, and an ArrayEncoder that calls EncodeTypeAny more than once gets separators between the elements.
@ssgreg
ssgreg force-pushed the fix/encoder-errors branch from d0daf49 to 5751321 Compare December 2, 2026 12:41
@ssgreg

ssgreg commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Force-pushed d0daf49 -> 5751321. An Any field whose value fails to marshal is no longer written as "ch":"<logf: ...>": the key is dropped and a chError string field holds the error, as zap does, so the field never changes type. Array elements keep the "<logf: ...>" string, since they have no key. New tests cover the failing field first, last, inside a group and in a cached logger Bag.

@ssgreg
ssgreg merged commit bea5187 into main Dec 2, 2026
6 checks passed
@ssgreg
ssgreg deleted the fix/encoder-errors branch December 2, 2026 12:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant