如何将catch()添加到在Node.js中执行更多代码的异步函数

时间:2019-04-08 20:17:06

标签: javascript node.js

我正在尝试从数据库中提取值并发送备用消息(通过https://slack.dev/node-slack-sdk/webhook)。如果松弛的Webhook无法解决,我希望它发布到工具监视通道,并希望将内置的Promise分辨率用于我的编码逻辑。如果我犯了一个愚蠢的错误,请原谅我,因为我完全不熟悉nodejs / javascript

我尝试将catch()追加到末尾,但我真的不知道从哪里开始。

const IncomingWebhook = require('@slack/webhook').IncomingWebhook;
var url = process.env.SLACK_WEBHOOK_URL;
var webhook = new IncomingWebhook(url);
const TOTAL_GHE_ISSUES = "10"
const GHE_ISSUE_NUMBERS = "90"

// Send the notification
if (url != "")

    (async () => {
    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 + "*"}}]}]
    });
    })();



else {console.log("No webhook provided");}

在else语句之前,我想添加一个catch函数,如果提供的webhook无法解析,则可以执行进一步的代码(在我的情况下,我希望它将消息发送到具有静态webhook的另一个松弛通道) 。我正在寻找任何帮助,因为我不确定从哪里开始。

1 个答案:

答案 0 :(得分:0)

您可能只是在追赶这样的异步功能

if (url != "")
  (async () => {
    // await webhook.send(bla bla)
    throw new Error('webhook.send error')
  })().catch(console.log); // Do console.log if error
else {
  console.log("No webhook provided");
}

或仅使用try / catch

if (url != "")
  (async () => {
    try {
      // await webhook.send(bla bla)
      throw new Error('webhook.send error')
    } catch (error) {
      console.log(error)
    }
  })();
else {
  console.log("No webhook provided");
}
相关问题