Last Updated: February 25, 2016
·
11.11K
· rottmann

Node.js Uncaught Exceptions

Typically in Node.js (JavaScript, or any other) you add many if-clause to intercept errors, or add many try-catch blocks (if possible because of callbacks).

Then you call your error handler that send an email to the developer or write the error to a file or database.

In a production system it is really important to capture uncaught exceptions too. E.g. a simple type conversion is missing, or a file is write protected, then your application stop working and you don't know why. Or you Application restart automatically and you don't see any error.

Capture Event

In Node.js an uncaughtException event is fired.

You can capture that event with a simple:

process.on("uncaughtException", function(err) { ... });

and add error handler in the callback function.

To stay informed about this kind of errors add a simple e-mail function with https://github.com/andris9/Nodemailer

Snippet

Here is a small snippet, that send an error Mail via your SMTP Mailserver.

var nodemailer = require("nodemailer");
var config = {
  mailMode: "SMTP",
  nodemailer: {
    auth: {
      user: "username",
      pass: "password"
    }
    host: "mail.your-domain.tld",
    port: 587,
    service: "yourMailService"
  },
  senderMail: "info@your-domain.tld",
  problemMail: "problem@your-domain.tld",
  serviceName: "yourAppName"
};

process.on("uncaughtException", function(err) {
  if(process.env.NODE_ENV === "production")
  {
    var mailer = nodemailer.createTransport(config.mailMode, config.nodemailer);
    var message = {
      from: config.senderMail,
      to: config.problemMail,
      subject: "Error in service: " + config.serviceName,
      text: (new Date()).toUTCString() + "\n\n" +
      err.message + "\n\n" +
      err.stack
    };
    mailer.sendMail(message, function() {
      process.exit(1);
    });
  }
  else
  {
    console.error((new Date()).toUTCString() + " uncaughtException: " + err.message);
    console.error(err.stack);
    process.exit(1);
  }
});

When you develop your application, an uncaught Error will be written to console.

2 Responses
Add your response

Please remember to not continue the process afterwards (as per example), beause your program will end up in an undefined state.

Also see:
http://nodejs.org/api/process.html#process_event_uncaughtexception

over 1 year ago ·

Yes you are right.
Not that somebody misunderstand me, it is only a simple way to get a notification when your application crash and must be restart (look at tools like nodemon, monit, ...).
Better (if possible) use external tools or services that inform you about errors.

over 1 year ago ·