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

Node.js中pm2-health未触发应用级错误邮件通知的问题求助

在Axios Catch块中实现应用级错误邮件通知

由于pm2-health仅能捕获运行时错误,对于Axios请求超时这类已被捕获的应用级错误,需要手动实现邮件通知逻辑。下面是基于nodemailer(Node.js常用邮件发送库)的具体实现方案:

步骤1:安装依赖

首先安装nodemailer:

npm install nodemailer

步骤2:封装邮件发送工具函数

创建可复用的错误通知邮件发送函数,根据你的邮箱服务商调整SMTP配置:

const nodemailer = require('nodemailer');

// 初始化邮件发送器,替换为你的邮箱SMTP配置
const transporter = nodemailer.createTransport({
  host: 'smtp.example.com', // 例如:smtp.qq.com、smtp.gmail.com
  port: 465, // SSL端口通常为465,非SSL为587
  secure: true, // true对应SSL端口,false对应非SSL
  auth: {
    user: 'your-alert-email@example.com', // 发送通知的邮箱
    pass: 'your-email-password-or-app-code' // 邮箱密码/应用专用密码
  }
});

// 发送错误通知邮件
async function sendErrorAlert(err) {
  const errorInfo = {
    message: err.message,
    type: err.name,
    stack: err.stack,
    time: new Date().toLocaleString('zh-CN')
  };

  const mailContent = {
    from: '应用错误警报 <your-alert-email@example.com>',
    to: 'admin@example.com', // 接收通知的邮箱
    subject: `应用错误:${err.code === 'ECONNABORTED' ? '请求超时' : '请求失败'}`,
    text: `检测到应用级错误:
错误信息:${errorInfo.message}
错误类型:${errorInfo.type}
发生时间:${errorInfo.time}

错误堆栈:
${errorInfo.stack}`,
    html: `<h2>应用错误警报</h2>
<p><strong>错误类型:</strong>${err.code === 'ECONNABORTED' ? '请求超时' : '请求失败'}</p>
<p><strong>错误信息:</strong>${errorInfo.message}</p>
<p><strong>发生时间:</strong>${errorInfo.time}</p>
<h3>错误堆栈详情:</h3>
<pre>${errorInfo.stack}</pre>`
  };

  try {
    await transporter.sendMail(mailContent);
    console.log('错误通知邮件已发送');
  } catch (mailErr) {
    console.error('发送错误邮件失败:', mailErr);
  }
}

步骤3:在Axios Catch块中调用通知函数

修改你的Axios请求代码,在catch块中触发邮件通知:

const axios = require('axios');
const qs = require('qs');

axios({
  url: process.env.ACCESS_TOKEN_API,
  proxy: {
    protocol: 'http',
    host: 'hostname',
    port: 8080,
  },
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: qs.stringify(params),
  timeout: 5000, // 5 seconds timeout
})
.then(response => response.data)
.then(data => {
  console.log(data);
})
.catch(err => {
  // 触发错误邮件通知
  sendErrorAlert(err);
  
  // 根据错误类型做针对性处理
  if (err.code === 'ECONNABORTED') {
    console.error('请求超时:', err.message);
  } else {
    console.error('请求失败:', err.message);
  }
});

注意事项

  • 邮箱配置:不同邮箱服务商的SMTP参数不同,比如QQ邮箱需开启SMTP服务并使用「应用专用密码」,Gmail需开启两步验证后生成应用密码。
  • 敏感信息:建议将邮箱账号、密码等敏感信息存入环境变量,避免硬编码在代码中。
  • 错误分类:可以根据err.code或err.response.status进一步区分错误类型,定制不同的邮件主题和内容。
  • 重试机制:生产环境中可给邮件发送逻辑添加重试,避免因临时网络问题导致通知丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:06:27