0

I'm trying to pull values from a database and send slack messages (via https://slack.dev/node-slack-sdk/webhook). If the slack webhook fails to resolve, I want it to post to a tool monitoring channel and want to use the built in Promise resolution for my coding logic. Please forgive me if I'm making a dumb mistake as I'm completely unfamiliar with nodejs/javascript

I've tried appending catch() to the end but I really do not know where to start.

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");}

Before the else statement, I'd like to add a catch function if the webhook provided does not resolve that can then execute further code (in my case I want it to send a message to another slack channel with a static webhook). I'm looking for any help as I'm not sure where to start.

  • 3
    It doesn't seem like you're getting much benefit from using `async/await` here when you could just `webhook.send({/* stuff */}).catch(err => /* deal with error */)` But if you need `async/await` you typically wrap it in `try/catch` for error handling. – Mark Apr 08 '19 at 20:21
  • You might want to have a look at https://stackoverflow.com/questions/44663864/correct-try-catch-syntax-using-async-await – Bergi Apr 09 '19 at 07:34

1 Answers1

0

You may just catch after async function like this

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");
}

or just use 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");
}
NV4RE
  • 173
  • 1
  • 13