Normally I just simply log the error, or maybe I'll do console.log(err.message), but one of our servicers returns a data dump of info. Since Javascript truncates objects the pertinent portion of the error is obscured.
So the full error will be like this
request:{ // thousands of lines
// ...
// several levels deep there will be a pertinent portion buried deep within the error
error:{
en: {
message:{
"Here is the super specific error info which I care about"
This logged will end up like this
request:{ // thousands of lines
Object // <- it's in there
Ideally I would just simply log the important part that I care about, but in order to even get to this part of the object I have to inspect the error console.log(util.inspect(err, false, null)), which delivers a data dump of 5000+ lines which contains our keys in numerous places.
At one point I was doing this
var errorMsgIs = "";
if (err.response && err.response.body && err.response.body.error && err.response.body.error.en) {
errorMsgIs = err.response.body.error.en
}
console.log(loggit, "Bank Error on Nodes.create inside addARInfo: ", err, errorMsgIs);
But that only works if the structure never changes based on the error.
Is the solution to come up with some sort of cleansing function to comb through all 5000 lines, level by level and check specifically for the keys, then do a .replace, I've thought about going that route.
What's the best way to log these massive errors so that I can get the pertinent data I need buried deep within the error while not exposing our keys into the logs?
Yes, you need to loop over the object properties and look for your data structure. With a recursive function, it's quite easy:
/**
* Retrieve an error message from an error object.
* @param {object} obj
* @returns {string | undefined}
*/
function getErrorMessage(obj) {
const props = Object.values(obj);
for (let i = 0; i < props.length; i++) {
const element = props[i];
if (typeof element === 'object') {
if (element.error?.en?.message) return element.error.en.message;
const result = getErrorMessage(element);
if (result) return result;
}
}
}
const data = {/* ... */}; // your data object
console.log(getErrorMessage(data));
Note that this is using ES2020+ syntax (for optional chaining). If you don't have access to that ES level, you can use your initial syntax:
if (element.error && element.error.en && element.error.en.message) return element.error.en.message;