i have a node.js server that i want to be able to handle exceptions without crashing, and i've got code kinda like the below. What i'm wanting to know, with all the event-driven awesomeness and callbacks and lambdas and all that, will my exceptions still be caught by my main entry point?
try {
http.get(..., function(results) {
// Might get an exception here
results.on('data', function () {
// Might also get an exception here
});
results.on('end', function () {
// Might also get an exception here
});
});
} catch(e) {
// Will the exceptions from the lambdas be caught here?
console.log('Nicely caught error: (' + e.name + '): ' + e.message);
}
Thanks
Exception handling is one of the powerful JavaScript features to handle errors and maintain a regular JavaScript code/program flow. An exception is an object with an explanation of what went amiss.
js receives a CPU bound task: Whenever a heavy request comes to the event loop, Node. js would set all the CPU available to process it first, and then answer other requests queued. That results in slow processing and overall delay in the event loop, which is why Node. js is not recommended for heavy computation.
It depends on the flow of control. Node.js puts emphasis on being asynchronous and one of the main drawbacks of asynchronicity is that the code doesn't flow in a way that you might be used to with a synchronized language.
In a synchronous language the caller is blocked while a function is waiting for some data. This makes the programmers job fairly simple because they can be guaranteed that when the function that's waiting for data returns, there will be data for the caller to consume.
It's the exact opposite in an asynchronous language, or with non-blocking I/O. In this case, the caller is blocked for the duration of the function call, however functions don't have to wait for data or I/O to complete before returning. This makes things slightly harder on the programmer because when an function call returns there are no guarantees about whether there will be data available. Hence, non-blocking I/O typically implies callback functions that get called when data is available to act on.
try/catch
blocks work with the call stack. That is, when an exception is thrown the runtime will unwind the call stack until it finds a catch
block that surrounds the call that threw the exception. But, since http.get
is a non-blocking call it exits immediately after registering some callbacks and processing continues. The callbacks are called in a separate "thread" and therefore the calls aren't nested within the original try/catch
block.
A diagram would really help explain things here but unfortunately I don't have one available to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With