In my server.js file i'm trying to log errors and not cause them to crash the app, this is the code im using
const server = app.listen(3000, () =>
console.log('Server Up and running')
);
process.on('unhandledRejection', (err, promise) => {
console.log(`Error: ${err}`);
server.close(() => process.exit(1));
})
when i produce an error instead of it logging the error and closing the server it just logs the error how it normally would and causes the app to crash. If you need more info let me know. Sorry if this is a dumb question
I suppose you know the difference between Unhandled Rejection and Uncaught Exception.
it just logs the error how it normally would
Because you're console logging the same error object!
Also don't use process.exit(). Because you might lose your logs. read more
Express docs explained how to do graceful shutdown, you can use similar approach.
Related
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.
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
I am very happy with logging using npm module morgan but not sure how to log system crash or system shutdown in node application. Is it possible? Please guide.
Thanks
You can use the Process API to watch for uncaught exceptions.
process
.on('unhandledRejection', (reason, p) => {
// Use your own logger here
console.error(reason, 'Unhandled Rejection at Promise', p);
})
.on('uncaughtException', err => {
// Use your own logger here
console.error(err, 'Uncaught Exception thrown');
// Optional: Ensure process will stop after this
process.exit(1);
});
For a detailed explanation check this answer to a similar question here on Stack Overflow. There's also this great blog post: https://shapeshed.com/uncaught-exceptions-in-node/.
As an extra, check this other one to send emails with the crash information: https://coderwall.com/p/4yis4w/node-js-uncaught-exceptions
I'm using a few external API's (some in timers, every minute or so) and sometimes I get some connection errors because of network problems or because the external systems are down for some reason. When I get this errors, the app restarts, and if the error persists the app continues restarting.
Any ideas on how can I ignore the connection error and keep the app running?
Code Example:
try {
var req = https.request(options, callback);
req.write(JSON.stringify(params));
req.end();
} catch (e) {
throw e;
}
Based on your code example. You're doing throw e inside your try catch. Essentially, you're catching an error and then throwing the error. Just do console.error(err) or however you want to handle that error, without throwing. This is what will cause your instance to stop.
Please note that the above "possible answer" questions does not contain an answer to my question. I am using require("http"). In that question the person is taking a socket input variable that they can put a handler on. I do not have the same variable.
I have a very simple server that I have written in Node.
var http = require("http");
var sys = require("sys");
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({
target: "someServer"
});
http.createServer(function(request, response) {
try {
proxy.web(request,response);
} catch (err) {
sys.puts("I caught an error!");
}
}).listen(5000);
When I leave my app running, it crashes. My command line says:
events.js:72
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at errnoException (net.js:900:11)
at TCP.onread (net.js:555:19)
It seems to crash not when server is serving files, but when it is waiting for a long time between requests.
While my code is a little more complex, I do have error catching on every callback.
Why is it crashing? What can I do?
In node, sprinkling try and catch everywhere is not the same as catching every error. (And in most cases, doing so is useless.) Asynchronous operations cannot throw useful exceptions because control long ago left the block of code that invoked the operation.
Instead, many objects emit an error event. The error event is a special case in that node will throw a "real" exception if there are no listeners for the event. Because this exception is thrown from code you do not and cannot control (ie wrap with try/catch), it goes uncaught and the process ends.
So if you do not add an error listener to sockets, a socket error will bring down the entire app.
However, your unhandled error is not coming from your http requests. The http module adds an error handler to every socket automatically, and re-emits the error as a clientError event on the Server. Because EventEmitters only throw when the event is named error, the fact that you don't handle clientError does not matter.
If we read http-proxy's documentation, we see that it also throws an error event, and you aren't listening for it. Thus, your app dies whenever there's an error fetching something from an upstream server.
Add an error handler.
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong.');
console.error(err);
});
Any time you see this error ("// Unhandled 'error' event"), it means you need to find out what is emitting an error event and add a listener to handle the error.