From d0707bd8371f584869b56252dcb27c01c9691655 Mon Sep 17 00:00:00 2001 From: Kyle Ross Date: Fri, 9 Apr 2021 16:05:15 -0400 Subject: [PATCH] feat(internal): add function to stub errors with a toJSON method --- lib/LogMessage.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/lib/LogMessage.js b/lib/LogMessage.js index f43a494..9cd356a 100644 --- a/lib/LogMessage.js +++ b/lib/LogMessage.js @@ -220,6 +220,35 @@ class LogMessage { ) ); } + + /** + * Stubs an Error or Error-like object to include a toJSON method. + * @static + * @param {Error} err An Error or Error-like object. + * @return {Error} + */ + static stubError(err) { + err.toJSON = function () { + const keys = [ + 'name', + 'message', + 'stack' + ].concat(Object.keys(err)); + + return keys.reduce((obj, key) => { + if(Object.prototype.hasOwnProperty.call(err, key)) { + const val = err[key]; + if(typeof val !== 'function') { + obj[key] = val; + } + } + + return obj; + }, {}); + }; + + return err; + } } LogMessage.symbols = symbols;