Why Won't Error Handling Work In Nodemailer?
I am trying to set up a really simple contact form with nodemailer and it works fine, but my issue is that it doesn't handle errors. The page should redirect if an error is thrown,
Solution 1:
I finally figured out a solution to this myself. Here is a wrapper function:
functionsendEmail(req) {
const name = req.body.name;
const email = req.body.email;
const msg = req.body.message;
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 587,
secure: false,
service: 'gmail',
auth: {
user: //left out,pass: process.env['GMAIL_PASS']
}
});
const mailOptions = {
from: //left outto: //left outsubject: 'Portfolio Inquiry',
text: `
Name: ${name}
Email: ${email}
Message:
${msg}`};
return transporter.sendMail(mailOptions);
}
Then the function call:
try {
awaitsendEmail(req);
return res.redirect('/about?send=success#contact')
} catch (err) {
return res.redirect('/about?send=fail#contact')
}
Because the sendMail
function returns a promise when no callback is given, you can call it in a try...catch
block.
Solution 2:
As stated already:
Because the sendMail function returns a promise when no callback is given, you can call it in a
try...catch
block.
sendMail
returns a promise, you can chain .then()
and .catch()
for handling like:
// async/await is not available in the global scope, so we wrap in an IIFE
(() => {
const result = await transporter
.sendMail(mailOptions)
.then(console.log)
.catch(console.error);
// do something with `result` if needed
})();
Post a Comment for "Why Won't Error Handling Work In Nodemailer?"