Skip to content

Instantly share code, notes, and snippets.

@aaira-a
Created April 11, 2017 00:49
Show Gist options
  • Save aaira-a/273422e057426d852e66a57e45bdd0b4 to your computer and use it in GitHub Desktop.
Save aaira-a/273422e057426d852e66a57e45bdd0b4 to your computer and use it in GitHub Desktop.
nodejs - stringify js error/object - stolen from http://stackoverflow.com/a/20405830
var stringifyError = function(err, filter, space) {
var plainObject = {};
Object.getOwnPropertyNames(err).forEach(function(key) {
plainObject[key] = err[key];
});
return JSON.stringify(plainObject, filter, space);
};
try {
require('net').connect(-1);
} catch(err) {
console.log(stringifyError(err, null, ''));
}
try {
doesNotExist;
} catch(err) {
console.log(stringifyError(err, null, '\n'));
}
try {
require('vm').runInThisContext('binary ! isNotOk');
} catch(err) {
console.log(stringifyError(err, null, '\n'));
}
try {
require('url').parse(() => {});
} catch(err) {
console.log(stringifyError(err, null, '\n'));
}
err = "";
console.log(stringifyError(err, null, '\n'));
err = [];
console.log(stringifyError(err, null, '\n'));
err = {'abc': true, 'def': 'something'};
console.log(stringifyError(err, null, '\n'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment