mod_rest: Improve error handling during format mapping
Prevents e.g. a nil, error return going directly into e.g. json
encoding, resulting in "null" being returned.
Further handling improvements down the line is needed.
--- a/mod_rest/mod_rest.lua Thu Apr 07 17:48:08 2022 +0200
+++ b/mod_rest/mod_rest.lua Thu Apr 07 17:49:08 2022 +0200
@@ -230,16 +230,21 @@
end
local function encode(type, s)
+ if type == "text/plain" then
+ return s:get_child_text("body") or "";
+ elseif type == "application/xmpp+xml" then
+ return tostring(s);
+ end
+ local mapped, err = jsonmap.st2json(s);
+ if not mapped then return mapped, err; end
if type == "application/json" then
- return json.encode(jsonmap.st2json(s));
+ return json.encode(mapped);
elseif type == "application/x-www-form-urlencoded" then
- return http.formencode(flatten(jsonmap.st2json(s)));
+ return http.formencode(flatten(mapped));
elseif type == "application/cbor" then
- return cbor.encode(jsonmap.st2json(s));
- elseif type == "text/plain" then
- return s:get_child_text("body") or "";
+ return cbor.encode(mapped);
end
- return tostring(s);
+ error "unsupported encoding";
end
local post_errors = errors.init("mod_rest", {