4

I have a nodejs application which uses the nodemailer plugin to send out emails. This works 99.99% of the time but yesterday the application hung up with following error in the PM2 logs.

mod.mailer: Error: connect ENETUNREACH 2a00:1450:400c:c04::6c:465 - Local (:::0)

I did't find a lot of information about this kind of error. It is entirely possible that there might have been a blip in the network connection. Below is the code for the module I wrote to transport emails. How would I catch this kind of error and ensure that the application doesn't hang up but rather retries to send the email.

var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport(process.env.TRANSPORT);

function mail(options) {
    transporter.sendMail({
        from: process.env.SUBDIRECTORY + '\@' + process.env.HOST + '\ \<geolytix@gmail.com\>',
        to: options.to,
        subject: options.subject,
        text: options.text
    }, function (err, info) {
        if (err) {
            console.log('mod.mailer: ' + err);
        }
        console.log('mod.mailer: ' + info.response);
    });
}

module.exports = {
    mail: mail
};
Harshal Bhamare
  • 372
  • 1
  • 6
  • 17
Dennis Bauszus
  • 1,624
  • 2
  • 19
  • 44

1 Answers1

0

That issue is an internal package catch that pops up when there is a network issue. So to resolve this, you must also put your code in try-catch block and recursively call your function

function mail(options) {
  try{
    transporter.sendMail({
        from: process.env.SUBDIRECTORY + '\@' + process.env.HOST + '\ \<geolytix@gmail.com\>',
        to: options.to,
        subject: options.subject,
        text: options.text
    }, function (err, info) {
        if (err) {
            console.log('mod.mailer: ' + err);
        }
        console.log('mod.mailer: ' + info.response);
    });
    
  } catch(err){
    console.log(err);
    mail(options)
  }
    
}

Note: This technique can also cause javascript stacking up on themselves indefinitely, and eating away at memory until they exceed the capacity of the engine, if the error keeps on popping.

One of the solutions is to get a check on the recursion which will drop if it reaches some limit.