如何修复try/catch中Slack Webhook的未处理Promise拒绝错误
问题分析与解决
这问题我之前也碰到过,核心原因是你没搞清楚webhook.send()的异步特性——它返回的是一个Promise对象,而你用的同步try/catch只能捕获同步代码里的错误,根本抓不到Promise被拒绝(reject)的情况,所以你的catch块完全没触发,错误直接变成了未处理的Promise拒绝。
解决方案1:用async/await配合try/catch(推荐,代码更清晰)
把你的逻辑包裹在一个async函数里,用await等待webhook.send()完成,这样同步的try/catch就能正常捕获Promise的错误了。
修改后的完整代码示例:
const TOTAL_GHE_ISSUES = "10"; // pulled from DB const GHE_ISSUE_NUMBERS = "90"; // pulled from DB const IncomingWebhook = require('@slack/webhook').IncomingWebhook; // 把所有逻辑放到async函数里 async function sendSlackAlert() { var url = SLACK_WEBHOOK_URL; var webhook = new IncomingWebhook(url); if (url !== "") { if (TOTAL_GHE_ISSUES !== "0") { try { // 用await等待异步操作完成 await webhook.send({ text: "*Daily Overdue Nessus Vulnerability Alert*", attachments: [{ color: "#FF0000", blocks: [{ type: "section", text: { type: "mrkdwn", text: "@here *" + TOTAL_GHE_ISSUES + "* Overdue Nessus Vulnerability issues reported \nOverdue Nessus Vulnerability GHE Issue Numbers: *" + GHE_ISSUE_NUMBERS + "*" } }] }] }); } catch(err) { console.log("Webhook Verification Failed", err); // 向监控频道发送告警,重新创建实例更稳妥 const monitoringWebhook = new IncomingWebhook(SLACK_MONITORING_URL); await monitoringWebhook.send({ text: "*Nessus Webhook Verification, please investigate broken webhooks:*", attachments: [{ color: "#FF0000", blocks: [{ type: "section", text: { type: "mrkdwn", text: `Broken webhook URL: *${SLACK_WEBHOOK_URL}*` } }] }] }); } } else { try { await webhook.send({ text: "*Daily Overdue Nessus Vulnerability Alert*", attachments: [{ color: "#36a64f", blocks: [{ type: "section", text: { type: "mrkdwn", text: "@here *NO* Overdue Nessus Vulnerabilities reported" } }] }] }); } catch(err) { console.log("Webhook Verification Failed", err); const monitoringWebhook = new IncomingWebhook(SLACK_MONITORING_URL); await monitoringWebhook.send({ text: "*Nessus Webhook Verification, please investigate broken webhooks:*", attachments: [{ color: "#FF0000", blocks: [{ type: "section", text: { type: "mrkdwn", text: `Broken webhook URL: *${SLACK_WEBHOOK_URL}*` } }] }] }); } } } else { console.log("No webhook provided"); } } // 调用async函数,同时捕获顶层可能的错误 sendSlackAlert().catch(err => console.error("Top-level error:", err));
解决方案2:用Promise的.catch()方法
如果你暂时不想用async/await,也可以直接在webhook.send()后面链式调用.catch()来处理错误,比如:
webhook.send({ // 你的消息内容 }).catch(err => { console.log("Webhook Verification Failed", err); // 处理监控频道告警 const monitoringWebhook = new IncomingWebhook(SLACK_MONITORING_URL); monitoringWebhook.send({/* 监控消息内容 */}).catch(err => console.error("Monitoring webhook failed:", err)); });
额外小提醒
- 不要重复复用同一个
webhook实例发送不同频道的消息,每次发送新频道都重新创建IncomingWebhook实例更稳妥。 - 错误处理里最好把错误详情也打印出来(比如
console.log("Webhook Verification Failed", err)),方便排查具体问题(比如URL无效、网络错误还是Slack返回的其他异常)。
内容的提问来源于stack exchange,提问作者Brandon Konieczny
相关产品推荐
相关产品推荐

