1
\$\begingroup\$

In this code I'm using nodemailer for sending otp email from my gmail account. I have also used ejs for creating html templates for emails.

This code works perfectly, but I am a bit concerned about how the code is written, particularly the use of try-catch for error handling.

Should I use try/catch in a promise if an express app level has level error handling? How can I make this code efficient?

const ejs = require("ejs");
const path = require("path");
const otpTemaplte = path.join(__dirname, "../public/views/otpemail.ejs");
const nodemailer = require("nodemailer");
const config = require("../config/config");
const transporter = nodemailer.createTransport(config.mailAuth);

const sendOTP = (to, otp) => {
return new Promise(async (resolve, reject) => {
    try {
    if (to === "undefined" && typeof otp == "undefined") {
        return new Error("invalid input for email");
    }
    const emailTemplate = await ejs.renderFile(otpTemaplte, {
        VERIFICATION_CODE: otp,
    });
    const result = await transporter.sendMail({
        from: "noreply@mail.com",
        to: to,
        subject: "OTP for email verification",
        html: emailTemplate,
    });
    if (result) {
        return resolve(result);
    }
    } catch (error) {
    return reject(error);
    }
});
};
module.exports = sendOTP;
\$\endgroup\$
0

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.