henit
henit

Reputation: 1180

Cleanup objects throwing error in constructor

Simplified example..

Javascript object constructor

var Foo = function() {
    someEventEmitter.on("event", this.someHandler);
    throw new Error("Unexpected error happening in a constructor");
}
// ...

var myObject;
try {
    myObject = new Foo();
} catch(e) {

}

Some real world case happens in a similar way to the example above. An object is attempted constructed, but the constructor (or possibly a parent constructor) throw an error. Could be programmed operational throw, or some bug like a reference error.

Before the exception is thrown, a listener or other data is set on/by the constructor. How can this be handled to avoid memory leak and events being emitted on the failed objects? Clean up the garbage, remove added listeners and such.

Upvotes: 0

Views: 464

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074989

You need to handle it in the constructor, either

  1. Ideally by doing everything that can throw before the things that you may need to clean up, which is nice and simple.

  2. If you can't do that, then you'll need to have a try...catch around your code to clean up.

Example of #2:

var Foo = function() {
    var emitterHooked = false;
    try {
        someEventEmitter.on("event", this.someHandler);
        emitterHooked = true;
        throw new Error("Unexpected error happening in a constructor");
    } catch (e) {
        if (emitterHooked) {
            try { 
                someEventEmitter.off("event", this.someHandler);
            } catch (e2) { }
        }
        throw e;
    }
};

Of course, with many event mechanisms, you don't really need the emitterHooked variable as removing one that has never been added is a no-op, but that was to emphasize the kinds of things you need to deal with when following that approach.

As you can see, that's really ugly, hence #1 above. :-)

Upvotes: 1

Related Questions