Why would an exception cause resource leaks in Node.js?

Why would an exception cause resource leaks in Node.js?

Problem

If you look at the beginning of the Node.js documentation for domains it states:

By the very nature of how throw works in JavaScript, there is almost never any way to safely “pick up where you left off”, without leaking references, or creating some other sort of undefined brittle state.

Again in the code example it gives in that first section it says:

Though we’ve prevented abrupt process restarting, we are leaking resources like crazy

I would like to understand why this is the case? What resources are leaking? They recommend that you only use domains to catch errors and safely shutdown a process. Is this a problem with all exceptions, not just when working with domains? Is it a bad practice to throw and catch exceptions in Javascript? I know it’s a common pattern in Python.

EDIT

I can understand why there could be resource leaks in a non garbage collected language if you throw an exception because then any code you might run to clean up objects wouldn’t run if an exception is thrown.

The only reason I can imagine with Javascript is if throwing an exception stores references to variables in the scope where the exception was thrown (and maybe things in the call stack), thus keeping references around, and then the exception object is kept around and never gets cleaned up. Unless the leaking resources referred to are resources internal to the engine.

UPDATE

I’ve Written a blog explaining the answer to this a bit better now. Check it out

Problem courtesy of: Justin Warkentin

Solution

Unexpected exceptions are the ones you need to worry about. If you don’t know enough about the state of the app to add handling for a particular exception and manage any necessary state cleanup, then by definition, the state of your app is undefined, and unknowable, and it’s quite possible that there are things hanging around that shouldn’t be. It’s not just memory leaks you have to worry about. Unknown application state can cause unpredictable and unwanted application behavior (like delivering output that’s just wrong — a partially rendered template, or an incomplete calculation result, or worse, a condition where every subsequent output is wrong). That’s why it’s important to exit the process when an unhandled exception occurs. It gives your app the chance to repair itself.

Exceptions happen, and that’s fine. Embrace it. Shut down the process and use something like Forever to detect it and set things back on track. Clusters and domains are great, too. The text you were reading is not a caution against throwing exceptions, or continuing the process when you’ve handled an exception that you were expecting — it’s a caution against keeping the process running when unexpected exceptions occur.

Solution courtesy of: Eric Elliott

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *