I have a Node.js server that is continually crashing without logging any kind of error message. Is this a typical scenario? How can I trap the error and log it before it crashes?
Sometimes poorly optimized server-side code can consume all your resources under normal operating conditions and cause your server to become overwhelmed and crash. Or the frontend code itself might be the source of the crash. If there's an infinite loop or you aren't handling all edge cases, your server could go down.
PM2 is a Node. js process manager that comes with a built-in load balancer. It helps facilitate production deployments and enables you to keep running applications alive indefinitely (even when accidents occur).
Node normally exits with code 0 when no more async operations are pending. process. exit(1) should be used to exit with a failure code.
A good start would be to setup, especially in production, before setting the listener for your server, an handler for the exceptions that logs the details. Look at here:
process.on('uncaughtException', function (exception) { console.log(exception); // to see your exception details in the console // if you are on production, maybe you can send the exception details to your // email as well ? });
If you are using Express.js, take a look at here to know how to see the full stack of your error (and eventually, again, send it to your email if you are on production). In that case, tell it to give you the full details before instantiating the listener:
var express = require('express'); // ... var app = express(); var errorHandler = require('errorhandler') // ... app.use(errorHandler({ dumpExceptions: true, showStack: true })); // then, set the listener and do your stuff...
2019 update: you'll need to install the errorHandler package
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