Warp the index file in Nodejs with try and catch - node.js

In my production env when an error is thrown in a docker container, it just kills the container but doesn't log the error. the only way I can log that error is to warp all the code in the index file with try-catch and then console it.
Does anyone know how costly it is performance-wise to warp all the code in a try-catch block in Nodejs?

I don't see any performance degradation when you wrap it in try..catch. Infact it is a best practice to handle your errors. Not handling means you are prone to errors and unexpected shut down of your applications. You should also have a look why the error is coming and try to fix the root problem. You can also take help of
inbuilt unhandledRejection listener to see all your unhandled errors.
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
// Application specific logging, throwing an error, or other logic here
});
https://nodejs.org/api/process.html#process_event_unhandledrejection

Related

Logging all unhandled exceptions in HAPI with Winston

I'm using Winston to log to file / seq information I specifically log using log.info or some other level. But I've noticed that when an unhandled exception occurs, it's not logged... I'm not really familiar with Nodejs and HAPI (need to perform some activity while my colleagues are on vacation).. but I was wondering if there's a sort of middleware where I can attach and let Winston log all HAPI stuff.
Thanks in advance
You can listen on uncaughtException and/or unhandledRejection of your current Node.js process to call you logger (here I simply called console.log):
process.on('uncaughtException', (err, origin) => {
console.log('Caught exception:', err, 'Exception origin:', origin);
});
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
});
However:
uncaughtException is a crude mechanism for exception handling intended to be used only as a last resort.
...
The correct use of uncaughtException is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process. It is not safe to resume normal operation after uncaughtException.
Read also Catch all uncaughtException for Node js app.

setTimeout never calls when exception is thrown in different context

Using node.js, when I run the program
setTimeout(() => console.log("Timed out"), 0);
console.log("finishing");
I see
finishing
Timed out
But when I add a throw before "finishing"
setTimeout(() => console.log("Timed out"), 0);
throw new Error();
console.log("finishing");
I see
throw new Error();
^
Error
at Object.<anonymous> ...(stack trace here)...
And I don't see any mention of "Timed out".
Why is that? Even though the initial context would throw, once the stack was freed up, I expected the callback I passed to setTimeout would still run.
Does having an uncaught exception cause all timeouts to get canceled? Is this feature documented somewhere?
If I have multiple timeouts, is there a way for me to make sure that all the other timeouts continue to run when they can even if one of them happens to throw?
Unlike a web application running on browser, a Node application runs as a process on top of Google V8 JavaScript Engine. If you look into https://nodejs.org/api/timers.html is states that
The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js Event Loop.
As the above statement explains, even though the same global functions are available in both cases, their implementations are different. Therefore when an uncaught exception occurs in a Node application, all code related to timeouts will stop as the process is terminated. The best way to handle this is to properly handle all exceptions. You can use the below code to capture all uncaught exceptions from the process level itself.
process.on('uncaughtException', function(error) {
console.log(error);
});

Capturing the source or line number of uncaught exception in node.js

I've a node.js express app running in IIS. I found that the app is crashing frequently due to some uncaught exception. Hence I used process.on('uncaughtException') to restart the service in case of uncaught exception. I'm able to get the error as "ECONNRESET" but I'm unable to get where this actually happened. Is there any way to capture the error source or line number which caused the exception?
Use the process.on('uncaughtException'… event which provides you with the Error object that contains the call stack
process.on('uncaughtException', function(err){
console.error(err.stack);
process.exit();
});

Sails - catch global adapter errors that crash the server

I'm trying to find the best place to handle connectivity errors, or any other global errors that crash the server.
What is the right place to catch adapter/global errors and not have them crash the server?
Specifically, I want to handle these types of errors in a graceful way:
Error spawning mySQL connection:
error: Hook failed to load: orm (Error: connect ECONNREFUSED)
error: Error encountered while loading Sails core!
error: Error: connect ECONNREFUSED
from the sails docs: http://sailsjs.org/#!documentation/config.500
thats the error handling sails exposes from within the config
if your error passes that, you can hook in there, otherwise you can hook in node's process
process.on('uncaughtException', function (err) {
if (err.toString() === 'Error spawning mySQL connection') {
//rende some error page
}
})
if the exception thrown is async the only way to catch it is trough process
do note however, that these kinds of errors are almost always unrecoverable, so crashing (and restarting) is the best approach
most modules loaded use local variables and expose only a subset of their internals trough module.exports, unloading a module and restarting its local code can be done, but you would need to unload all dependant modules and all modules holding references to it also. Thats why the normal approach is to let it crash

Debugging stray uncaught exceptions (ECONNRESET) in a node cluster

In my node.js app which uses the cluster module, I'm intermittently seeing errors like this:
events.js:71
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at errnoException (net.js:863:11)
at TCP.onread (net.js:524:19)
This brings down my whole app, and so far the only way I've been able to deal with these is by binding a process.on('uncaughtException'). I'd like to figure out the underlying cause, but the above stack trace is pretty useless.
Is there some way to figure out what's causing these exceptions?
I should note that I'm seeing these only in the cluster master, not the workers, which leads me to suspect that they have something to do with the way the cluster modules does its magic in distributing connections to workers.
This answer was helpful: https://stackoverflow.com/a/11542134/233370
Basically, I installed longjohn and was then able to get the full async stack trace to figure out the underlying cause (rabbit.js in my case).
It seems that express enabled keep-alive by default.
In order to close connection after response you can add
res.set("Connection", "close");
Alternatively you can add a middleware in your app to close connection after each response:
app.use(function(req, res, next) {
res.set("Connection", "close");
next();
});

Resources