0
Schedule error handler
One script reply has been approved by the moderators Verified
Created by hugo697 450 days ago Viewed 33908 times
0
Submitted by hugo697 Deno
Verified 450 days ago
1
import { WebClient } from "https://deno.land/x/slack_web_api@1.0.0/mod.ts";
2
import dayjs from "npm:dayjs";
3

4
type Slack = {
5
  token: string;
6
};
7

8
function formatError(error: any) {
9
  if (error.stack && error.name && error.message) {
10
    return `*${error.name}: ${error.message}*\`\`\`\n${error.stack}\n\`\`\``;
11
  } else {
12
    return `\`\`\`\n${JSON.stringify(error, null, 2)}\n\`\`\``;
13
  }
14
}
15

16
export async function main(
17
  path: string, // The path of the script or flow that errored
18
  is_flow: boolean, // Whether the runnable is a flow
19
  schedule_path: string, // The path of the schedule
20
  error: object, // The error details
21
  started_at: string, // The start datetime of the latest job that failed
22
  failed_times: number, // Minimum number of times the schedule failed before calling the error handler
23
  slack: Slack,
24
  channel: string,
25
) {
26
  const baseUrl = Deno.env.get("WM_BASE_URL");
27
  const scheduleUrl = baseUrl + "/runs?schedule_path=" +
28
    encodeURIComponent(schedule_path);
29
  const runnableUrl = baseUrl + (is_flow ? "/flows/get/" : "/scripts/get/") +
30
    path;
31
  const web = new WebClient(slack.token);
32

33
  await web.chat.postMessage({
34
    channel,
35
    text: `Schedule ${schedule_path} failed ${
36
      failed_times > 1 ? (failed_times + " times in a row") : ""
37
    }`,
38
    blocks: [
39
      {
40
        "type": "section",
41
        "text": {
42
          "type": "mrkdwn",
43
          "text": `*Schedule <${scheduleUrl}|${schedule_path}> failed*${
44
            failed_times > 1 ? (" " + failed_times + " times in a row") : ""
45
          }:\n- ${is_flow ? "Flow" : "Script"}: <${runnableUrl}|${path}>`,
46
        },
47
      },
48
    ],
49
    attachments: [
50
      {
51
        color: "#ff0000",
52
        "blocks": [{
53
          "type": "section",
54
          "text": {
55
            "type": "mrkdwn",
56
            "text": `Last failure at: ${
57
              dayjs(started_at).format("DD.MM.YYYY HH:mm (Z)")
58
            }\n${formatError(error)}`,
59
          },
60
        }],
61
      },
62
    ],
63
  });
64
}
65