From 4eb194a2b10194f3ac1a4c8914d725aa90da265e Mon Sep 17 00:00:00 2001 From: Kunal Pathak Date: Tue, 14 Mar 2017 17:48:28 -0700 Subject: [PATCH] lib: Use regex to compare error message To make node engine agnostic, use better comparison method for error message. Lazily populate the `circular reference` error message thrown by `JSON.stringify()` which can be used to compare the error message thrown. PR-URL: https://github.com/nodejs/node/pull/11854 Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen Reviewed-By: Sakthipriyan Vairamani Reviewed-By: James M Snell Reviewed-By: Brian White --- lib/util.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/util.js b/lib/util.js index b243c81dd50..80195c26722 100644 --- a/lib/util.js +++ b/lib/util.js @@ -38,14 +38,21 @@ const inspectDefaultOptions = Object.seal({ breakLength: 60 }); -const CIRCULAR_ERROR_MESSAGE = 'Converting circular structure to JSON'; - +var CIRCULAR_ERROR_MESSAGE; var Debug; function tryStringify(arg) { try { return JSON.stringify(arg); } catch (err) { + // Populate the circular error message lazily + if (!CIRCULAR_ERROR_MESSAGE) { + try { + const a = {}; a.a = a; JSON.stringify(a); + } catch (err) { + CIRCULAR_ERROR_MESSAGE = err.message; + } + } if (err.name === 'TypeError' && err.message === CIRCULAR_ERROR_MESSAGE) return '[Circular]'; throw err;