Search code examples
javascriptnode.jserror-handlingprototypev8

Call function at native Error object's construction


In the following code example :

var oldConstructor = Error.constructor;
Error.constructor = function() {
    console.log('Constructor');
    oldConstructor.apply(null, arguments);
};
var a = new Error('ok');

Why isn't 'Constructor' printed ?

  • How can I run a function every time a native Error object's constructor is called ?

The goal I'm trying to achieve is that rather than bubbling Errors up the callback chain of the different modules used in my code base (mongoose, express.js, ...etc), I just want every error to emit an event or call a method (maybe with an Observer pattern).

I'm trying to solve the problem this way rather than modifying every line of code creating a new Error object.

Thanks in advance !


Solution

  • Error.constructor is a reference to the Function function, because Error is a function and functions are constructed by Function.

    You could have done:

    var oldError = Error;
    Error = function( arg ) {
        console.log('Constructor');
        return new oldError( arg );
    };
    

    But this is not guaranteed to work at all as modules could have stored a local reference to the Error constructor if they run before your code.

    You could instead use the uncaughtexception event