【问题标题】:Error handling not working for Nodemailer in Express错误处理不适用于 Express 中的 Nodemailer
【发布时间】:2021-02-07 12:59:15
【问题描述】:

我有一个使用 nodemailer 阅读邮件的功能:MailRead.js

exports.sendMailService = async (mailOptions) => {
    return new Promise((resolve, reject) => {
        mailOptions.from = 'someemail@some.com'
        const transporter = nodemailer.createTransport({
            service: some,
            auth: {
                user: 'somemail@some.com',
                pass: 'password'
            }
        });
        transporter.sendMail(mailOptions, function (error, info) {
            if (error) {
                console.log("error is " + error);
                resolve(false); // or use rejcet(false) but then you will have to handle errors
            }
            else {
                console.log('Email sent: ' + info.response);
                resolve(true);
            }
        });
    })
}

当我在控制器中调用此函数时:sendController.js

exports.sendMail = async (req, res, next) => {
    const mailBody = req.body
    try{
        await sendMailService(mailOptions)
        //if I do this:
        //const mailSent = await sendMailService(mailOptions)
        //if every credential is correct it mailSent displays true if not credentials false it gives 
        //false
        //but I want to handle error not just check for condition.
    }catch (err){ //not coming to catch part
        next(ApiError.badClientError('Bad Credentials')); //some function to handle error
            return;
    }
};

调用api时:触发上述函数:

Apisample:

api.post('sendmail',sendMail);

我也试过this SO:但我不认为它对我有用。

那么对于虚假凭证有什么建议应该去catch语句吗?

【问题讨论】:

    标签: node.js express nodemailer


    【解决方案1】:

    您的sendMail() 函数假设对sendMailService() 的调用失败将拒绝它返回的承诺。但是,如果出错,您的 sendMailService() 函数会调用 resolve(false),而不是 reject(someError)。因此,您的 await sendMailService() 永远不会抛出,并且您永远不会到达您的 catch 块。

    如果您因错误而拒绝,那么它将进入您的 catch 块:

    exports.sendMailService = async (mailOptions) => {
        return new Promise((resolve, reject) => {
            mailOptions.from = 'someemail@some.com'
            const transporter = nodemailer.createTransport({
                service: some,
                auth: {
                    user: 'somemail@some.com',
                    pass: 'password'
                }
            });
            transporter.sendMail(mailOptions, function (error, info) {
                if (error) {
                    console.log("error is ", error);
                    // reject the returned promise with the error
                    reject(error);
                } else {
                    console.log('Email sent: ' + info.response);
                    resolve(true);
                }
            });
        })
    }
    

    【讨论】:

    • 非常感谢......对不起,我终于明白我犯错的地方......
    猜你喜欢
    • 2016-12-29
    • 2021-12-23
    • 2017-04-28
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多