Created
September 29, 2021 19:45
-
-
Save DinoChiesa/824869c47bcba5422d7a70e821d97b35 to your computer and use it in GitHub Desktop.
diagnose JSON.stringify failure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* jshint esversion:6, node:false, strict:implied */ | |
/* global print, context */ | |
function createPartialCopy(obj, partialPropertyList) { | |
// create new "partial copy" with only a subset of properties | |
return partialPropertyList.reduce(function(a, prop) { | |
a[prop] = obj[prop]; | |
return a; | |
}, {}); | |
} | |
function serializeOnePart(obj) { | |
// create new "sub object" with only the keys from part1 | |
try { | |
return JSON.stringify(obj); | |
} | |
catch (exc1) { | |
var props = Object.keys(obj); | |
if (props.length > 1) { | |
print("stringify still broken within this subset: " + JSON.stringify(props)); | |
return false; | |
} | |
else { | |
context.setVariable('json_stringify_status', 'broken toplevel property: ' + props[0]); | |
return 1; // terminate | |
} | |
} | |
} | |
function diagnoseStringify(obj) { | |
var props = Object.keys(obj); // [ "message", "token",..... ] | |
// split the list of toplevel properties | |
var part1Props = props.slice(0, props.length / 2); | |
var part2Props = props.slice(props.length / 2); | |
// Now, create "partial copies" of the object, and | |
// try to serialize each one. This will narrow the error. | |
// first half of property set | |
var part1 = createPartialCopy(obj, part1Props); | |
var r1 = serializeOnePart(part1); | |
if (r1 === false) { | |
// recurse | |
diagnoseStringify(part1); | |
} | |
// second half | |
var part2 = createPartialCopy(obj, part2Props); | |
var r2 = serializeOnePart(part2); | |
if (r2 === false) { | |
// recurse | |
diagnoseStringify(part2); | |
} | |
} | |
var payload = ....; | |
try { | |
// in 90% of the cases, this succeeds | |
var result = JSON.stringify(payload, null, 2); | |
context.setVariable('json_stringify_status', 'success, first cycle.'); | |
} | |
catch(exc1) { | |
// Possibly a runtime permission error. | |
// We may lose the log message here, but this will help diagnose. | |
diagnoseStringify(payload); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment