Created
May 10, 2025 07:04
-
-
Save presmihaylov/7406b79e5285561ae08f29de52da1ae9 to your computer and use it in GitHub Desktop.
Simple slack alerts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { Result } from "true-myth"; | |
export function newSlackAlertInterceptor(args: { | |
slackWebhookUrl: string; | |
environment: string; | |
appName: string; | |
logsUrl: string; | |
}) { | |
const { slackWebhookUrl, environment, appName, logsUrl } = args; | |
const baseParams = { | |
slackWebhookUrl, | |
type: "error", | |
serviceName: appName, | |
environment, | |
logsUrl, | |
} as const; | |
return { | |
withSlackAlertOnErr: async <T, E>(f: () => Promise<Result<T, E>>): Promise<Result<T, E>> => { | |
try { | |
const r = await f(); | |
if (r.isErr) { | |
await sendSlackAlert({ | |
...baseParams, | |
errorDetails: r.error, | |
}); | |
} | |
return r; | |
} catch (exception) { | |
await sendSlackAlert({ | |
...baseParams, | |
errorDetails: exception, | |
}); | |
throw exception; | |
} | |
}, | |
}; | |
} | |
async function sendSlackAlert(args: { | |
slackWebhookUrl: string; | |
type: "error" | "warn"; | |
serviceName: string; | |
environment: string; | |
logsUrl: string; | |
errorDetails: unknown; | |
}): Promise<void> { | |
const { slackWebhookUrl, type, serviceName, environment, errorDetails, logsUrl } = args; | |
const emoji = type === "error" ? ":rotating_light:" : ":warning:"; | |
const title = type === "error" ? "Error received" : "Warning received"; | |
const errorJson = JSON.stringify(errorDetails, null, 2); | |
const payload = { | |
blocks: [ | |
{ | |
type: "header", | |
text: { | |
type: "plain_text", | |
text: `${emoji} ${environment === "dev" ? "[dev]" : ""} ${title}`, | |
emoji: true, | |
}, | |
}, | |
{ | |
type: "section", | |
fields: [ | |
{ | |
type: "mrkdwn", | |
text: `*Service:* ${serviceName}`, | |
}, | |
{ | |
type: "mrkdwn", | |
text: `*Environment:* ${environment}`, | |
}, | |
], | |
}, | |
{ | |
type: "section", | |
text: { | |
type: "mrkdwn", | |
text: "*Details:*\n```" + errorJson + "```", | |
}, | |
}, | |
{ | |
type: "section", | |
text: { | |
type: "mrkdwn", | |
text: `:link: <${logsUrl}|View logs>`, | |
}, | |
}, | |
], | |
}; | |
try { | |
const response = await fetch(slackWebhookUrl, { | |
method: "POST", | |
headers: { "Content-Type": "application/json" }, | |
body: JSON.stringify(payload), | |
}); | |
if (!response.ok) { | |
console.error(`Slack webhook call failed: ${response.status} ${response.statusText}`); | |
} | |
} catch (error) { | |
console.error("Slack webhook call error:", error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment