Skip to content

Commit

Permalink
fix: fix handling of non JSON serializable values
Browse files Browse the repository at this point in the history
In all cases string should be returned
  • Loading branch information
medikoo committed Jun 5, 2018
1 parent 2ed64a3 commit 12543a4
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
8 changes: 5 additions & 3 deletions modifiers/j.js
Expand Up @@ -13,11 +13,13 @@ var CIRCULAR_JSON_ERROR_MESSAGE = (function () {

module.exports = function (value/*, placeholder, argIndex, args*/) {
try {
return JSON.stringify(value, null, 2);
var result = JSON.stringify(value, null, 2);
if (typeof result === "string") return result;
return "<non serializable>";
} catch (e) {
if (e.message === CIRCULAR_JSON_ERROR_MESSAGE) {
return "<Circular non-JSON serializable value>";
return "<circular>";
}
return "<Non-serializable to JSON value>";
return "<invalid>";
}
};
3 changes: 2 additions & 1 deletion test/modifiers/j.js
Expand Up @@ -6,9 +6,10 @@ var test = require("tape")
test("Should resolve", function (t) {
t.equal(modifier({ foo: "bar" }), "{\n \"foo\": \"bar\"\n}", "JSON string for JSON object");
var obj = { toJSON: function () { throw new Error("foo"); } };
t.equal(modifier(obj)[0], "<", "meaningful error string for non-serializable value");
t.equal(modifier(obj)[0], "<", "meaningful error string for invalid value");
obj = {};
obj.obj = obj;
t.equal(modifier(obj)[0], "<", "meaningful error for circular references");
t.equal(modifier()[0], "<", "meaningful error for non serializable values");
t.end();
});

0 comments on commit 12543a4

Please sign in to comment.