You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sendgrid发送邮件失败时async await未捕获异常代码继续执行问题求助

问题根因

你在FreshleafVerificationEmail异步方法内部已经通过.catch()捕获了Sendgrid发送邮件抛出的所有异常,且catch分支中仅做了错误日志打印,没有将错误重新向上抛出。这就导致该异步函数返回的Promise永远是resolved状态,外层的try/catch逻辑无法感知到邮件发送失败的异常,因此会继续执行后续的保存配置、保存用户、返回成功响应的代码。

修复方案

你可以根据业务需求选择以下任意一种方案修改:

方案1:移除内部错误捕获,让异常直接透传到外层

直接删除sgMail.send后的.then和.catch回调,错误会自动向上传递给外层的try/catch处理:

const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)

module.exports = {
  FreshleafVerificationEmail: async(receiver) => {
    const msg = {
      to: receiver,
      from: 'xxxx@xxxx.com',
      subject: 'Verifieer uw email adres - FreshLeaf',
      text: 'Verifieer uw email adres door te klikken op de onderstaande link'
    }
    const response = await sgMail.send(msg)
    console.log(response[0].statusCode)
    console.log(response[0].headers)
  }
}

方案2:内部保留错误日志,手动重新抛出异常

如果需要在邮件服务内部先打印错误日志,在catch分支最后新增throw error把异常向上抛出即可:

const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)

module.exports = {
  FreshleafVerificationEmail: async(receiver) => {
    const msg = {
      to: receiver,
      from: 'xxxx@xxxx.com',
      subject: 'Verifieer uw email adres - FreshLeaf',
      text: 'Verifieer uw email adres door te klikken op de onderstaande link'
    }
    await sgMail
    .send(msg)
    .then((response) => {
      console.log(response[0].statusCode)
      console.log(response[0].headers)
    })
    .catch((error) => {
      console.log(error)
      // 手动抛出错误,触发外层try/catch的异常处理逻辑
      throw error
    })
  }
}

修改后只要Sendgrid发送邮件失败,就会进入外层catch分支,返回400错误响应,不会执行后续的数据库保存操作。

内容的提问来源于stack exchange,提问作者mariodelta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:24:05