Search code examples
javascriptloggingpropertiesruntime-errorclone

How to clone a javascript Error into a standard object


Specifically, I'd like to convert a Javascript error to an object whose properties can be listed, and hence console.logged.

try {
    throw new Error('418 : Blue Teapot of Death');
} catch (error) {
    for (var k in arg) { console.log('Key found: ' + k); } // Outputs nothing
}

EDIT:

Using @YeahBoy solution, there is the final solution I adopted, using lodash pick function :

var copy_with_enumerable_properties = function (obj) {
    var props = Object.getOwnPropertyNames(obj); // Include non-enumerable properties
    return _.pick(obj, props);
};

try {
    throw new Error('418 : Blue Teapot of Death');
} catch (error) {
    var error_obj = copy_with_enumerable_properties(error);
    error_obj.stack = error_obj.stack.split('\n');

    console.log(JSON.stringify(error_obj, null, 2));
}

Solution

  • Try this.

    try {
        throw new Error('418 : Blue Teapot of Death');
    } catch (error) {
    
        var prop = Object.getOwnPropertyNames(error);
        for (var k in prop) { console.log('Key found: ' + prop[k]); }
    }