fix: json encode and decode use error() instead of nil, err #25

Closed
opened 2026-05-25 19:10:26 +02:00 by michael · 2 comments
Owner

Problem

encode_value is a recursive local function that calls error() on
unsupported types. Returning nil, err through all recursion levels is
not trivial.

Proposed fix

Wrap the top-level call in builtin_encode with pcall:

local ok, result = pcall(encode_value, value, ...)
if not ok then return nil, "[ERROR] json: " .. result end
return result

See also

## Problem `encode_value` is a recursive local function that calls `error()` on unsupported types. Returning nil, err through all recursion levels is not trivial. ## Proposed fix Wrap the top-level call in `builtin_encode` with pcall: local ok, result = pcall(encode_value, value, ...) if not ok then return nil, "[ERROR] json: " .. result end return result ## See also - DAW/daw-lua-common#23 (same pattern in yaml.lua)
michael changed title from fix: encode_value uses error() instead of nil, err to fix: json encode and decode use error() instead of nil, err 2026-05-25 19:11:49 +02:00
Author
Owner

Scope expanded: decode.lua has the same pattern in all three backends (cjson, dkjson, pure-lua). Fix must cover both encode_value and builtin_decode plus the cjson/dkjson wrappers.

Scope expanded: decode.lua has the same pattern in all three backends (cjson, dkjson, pure-lua). Fix must cover both encode_value and builtin_decode plus the cjson/dkjson wrappers.
Author
Owner

builtin_decode's four mutually-recursive functions (decode_string/object/array/value) now thread (value, err) explicitly -- err checked separately from value, since JSON null legitimately decodes to nil. Same pattern applied to encode_value. Also fixed: the cjson branch's pcall(cjson.decode, ...) was catching the error and immediately re-throwing it (error(result)) -- now returns nil, err. cjson encode was previously unprotected (M.encode = cjson.encode directly); now wrapped in pcall for parity with decode.

builtin_decode's four mutually-recursive functions (decode_string/object/array/value) now thread (value, err) explicitly -- err checked separately from value, since JSON null legitimately decodes to nil. Same pattern applied to encode_value. Also fixed: the cjson branch's pcall(cjson.decode, ...) was catching the error and immediately re-throwing it (error(result)) -- now returns nil, err. cjson encode was previously unprotected (M.encode = cjson.encode directly); now wrapped in pcall for parity with decode.
michael 2026-07-19 17:55:26 +02:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
DAW/daw-lua-common#25
No description provided.