te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Why won't error handling work in nodemailer? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why won't error handling work in nodemailer? - Stack Overflow

programmeradmin4浏览0评论

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, but instead the redirect does not happen and the app stops running. I cannot for the life of me figure out why this is happening. Here is my code:

if (req.method === 'POST') {
  const name = req.body.name;
  const email = req.body.email;
  const msg = req.body.message;

  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'myemail', // left out here
      pass: process.env['GMAIL_PASS']
    }
  });

  const mailOptions = {
    from: 'myemail', // left out here
    to: 'myemail', // left out here
    subject: 'Portfolio Inquiry',
    text: `
          Name: ${name}
          Email: ${email}
          Message:${msg}`
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      // If an error is thrown, it should redirect back to the page with a fail message
      return res.redirect('/about?send=fail#contact');
    } else {
      return res.redirect('/about?send=success#contact');
    }
  });
}

If I introduce an error into the script by menting out something important or just throwing an error, as I said the error handling block in the sendMail callback doesn't do anything. As I said, it does properly work and send the email, but if something went wrong I definitely want my user to know about it. Could anyone help me understand how to correct this issue?

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, but instead the redirect does not happen and the app stops running. I cannot for the life of me figure out why this is happening. Here is my code:

if (req.method === 'POST') {
  const name = req.body.name;
  const email = req.body.email;
  const msg = req.body.message;

  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'myemail', // left out here
      pass: process.env['GMAIL_PASS']
    }
  });

  const mailOptions = {
    from: 'myemail', // left out here
    to: 'myemail', // left out here
    subject: 'Portfolio Inquiry',
    text: `
          Name: ${name}
          Email: ${email}
          Message:${msg}`
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      // If an error is thrown, it should redirect back to the page with a fail message
      return res.redirect('/about?send=fail#contact');
    } else {
      return res.redirect('/about?send=success#contact');
    }
  });
}

If I introduce an error into the script by menting out something important or just throwing an error, as I said the error handling block in the sendMail callback doesn't do anything. As I said, it does properly work and send the email, but if something went wrong I definitely want my user to know about it. Could anyone help me understand how to correct this issue?

Share Improve this question edited May 2, 2020 at 15:57 Saeed 5,4883 gold badges29 silver badges41 bronze badges asked May 2, 2020 at 15:47 Michael AlexanderMichael Alexander 4801 gold badge4 silver badges16 bronze badges 5
  • 1 I can't find "res" variable here? – Kapil Raghuwanshi Commented May 2, 2020 at 16:00
  • I only included the block that handles a POST request. The res variable is in scope. My bad for not including the whole controller. – Michael Alexander Commented May 2, 2020 at 16:03
  • Just check this link once - stackoverflow./questions/56508261/… – Kapil Raghuwanshi Commented May 2, 2020 at 16:06
  • I tried that solution. Didn't work. I also tried writing a wrapper function that returns false on error, else true but the function always returns false, even when the email was sent. I'm pletely confused and frustrated. – Michael Alexander Commented May 2, 2020 at 16:39
  • I figured out a way to work it. If you leave out the callback it returns a promise. So I wrapped it in a function that returns the sendMail function without the callback, and then call the wrapper function in a try...catch block and that works for handling the error. – Michael Alexander Commented May 2, 2020 at 17:07
Add a ment  | 

2 Answers 2

Reset to default 7

I finally figured out a solution to this myself. Here is a wrapper function:

function sendEmail(req) {
    const name = req.body.name;
    const email = req.body.email;
    const msg = req.body.message;

    const transporter = nodemailer.createTransport({
        host: 'smtp.gmail.',
        port: 587,
        secure: false,
        service: 'gmail',
        auth: {
            user: //left out,
            pass: process.env['GMAIL_PASS']
        }
    });

    const mailOptions = {
        from: //left out
        to: //left out
        subject: 'Portfolio Inquiry',
        text: `
Name: ${name}
Email: ${email}
Message:

${msg}`};

    return transporter.sendMail(mailOptions);
}

Then the function call:

try {
   await sendEmail(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.

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
})();
发布评论

评论列表(0)

  1. 暂无评论