Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try/catch issues with nested functons in javascript

I'm having a scenario like below:

try {
   top();
} catch(e) {
   console.log(e);
}

function top() {
    nestedFunc1();
}

function nestedFunc1() {
    nestedFunc2();
}

function nestedFunc2() {
 // this function throws an exception.
}

my catch block doesn't get executed whenever an exception is thrown in my node script. Is this behaviour expected or i'm missing something here.

like image 935
Lovepreet Singh Avatar asked Mar 12 '26 03:03

Lovepreet Singh


1 Answers

With the code above, an exception from nestedFunc2 will definitely be caught by that try/catch block.

My suspicion is that what you really have is an exception in an asynchronous callback:

try {
    someNodeAPIFunction((err, result) => {
        // Exception thrown here
    });
} catch (e) {
    console.log(e);
}

If so, then yes, it's perfectly normal that the try/catch there doesn't catch the exception, because that code has already finished running. The callback is called later. The only thing that can catch the exception is the code in someNodeAPIFunction that calls the callback.

This is one of the reasons callback APIs are awkward to work with.

In any vaguely-recent version of Node.js, you can use async/await to simplify things. Node.js provides Promise-enabled versions of some of its API functions now (in particular the fs.promises module) and also provides the promisify utility function that you can use to turn a standard Node.js callback-style function into one that returns a promise. So for instance, with the above:

const someNodeAPIFunctionPromisified = util.promisify(someNodeAPIFunction);

Then, in an async function, you could do this:

try {
    const result = await someNodeAPIFunctionPromisified();
    // Exception thrown here
} catch (e) {
    console.log(e);
}

...and the exception would be caught, because async functions let you right the logical flow of your code even when dealing with asynchronous results.

More about async functions on MDN.

like image 154
T.J. Crowder Avatar answered Mar 13 '26 16:03

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!