In Node when I trigger another method(for sending email using nodemailer) from the main method, why the console.log of the error in sending email does not show up. I am testing the method for an invalid email ID. I do get an delivery failure email in my inbox immediately - but in Node the console log does not catch it - Why is this so?. I was hoping to see atleast one of the catch(error) console statement
Main Method:
// some code
try {
await sendOtpEmail(candidate.email, otp, reqHost)
console.log('OTP email being processed');
} catch(error) {
console.log('register-update-apply sendOtpEmail error:', error)
throw 'OTP Email Error:' + error
}
method 2:
async function sendOtpEmail(email, otp, reqHost) {
// prepare email
try{
await sendEmail({
to: email,
subject: appName + ' Verification OTP',
html: message
});
} catch(error) {
console.log('register-update-apply sendOtpEmail error:', error)
}
}
method 3:
async function sendEmail({ to, subject, html}) {
console.log('helper - sendEmail')
const copyMailServerOptions = JSON.parse(JSON.stringify(config.hpMailServerOptions));
const transporter = nodemailer.createTransport(copyMailServerOptions);
let sendEmail = true;
const xFrom = copyMailServerOptions.auth.user
transporter.verify(function(error, success) {
if (error) {
sendEmail = false;
console.log('email transporter error', error);
throw 'email transporter error: ' + error
} else {
// console.log('no email sending error');
}
});
if(sendEmail) {
try{
await transporter.sendMail({ xFrom, to, subject, html });
} catch(error){
console.log('transporter.sendMail to: ' + to + '. Error: ' + error)
}
}
}
console output
helper - sendEmail
OTP email being processed
It seems like the issue might be related to the asynchronous nature of the transporter.verify method in your sendEmail function. The transporter.verify method doesn't throw an error in a way that can be caught by the try...catch block in the sendOtpEmail function. Instead, it executes the callback function provided to it.
const util = require('util');
In this modification, the sendEmail function now returns a Promise that resolves when the email is successfully sent or rejects if there's an error during either verification or sending. This allows you to use try...catch blocks or .catch() to handle errors in the caller function.