|
| 1 | +import { posthog, type Properties } from "posthog-js"; |
| 2 | + |
| 3 | +let initialized = false; |
| 4 | + |
| 5 | +const doInitPostHog = (): void => { |
| 6 | + if (initialized) return; |
| 7 | + if ( |
| 8 | + !process.env.NEXT_PUBLIC_POSTHOG_KEY || |
| 9 | + !process.env.NEXT_PUBLIC_POSTHOG_HOST |
| 10 | + ) { |
| 11 | + throw new Error("PostHog environment variables are not set"); |
| 12 | + } |
| 13 | + posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, { |
| 14 | + /* eslint-disable @typescript-eslint/naming-convention */ |
| 15 | + api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, |
| 16 | + capture_pageview: false, |
| 17 | + /* eslint-enable @typescript-eslint/naming-convention */ |
| 18 | + }); |
| 19 | + initialized = true; |
| 20 | +}; |
| 21 | + |
| 22 | +const NON_WORD = /\W+/g; |
| 23 | +export const internalError = ({ |
| 24 | + error, |
| 25 | + type, |
| 26 | + context, |
| 27 | + forceSendInDev = false, |
| 28 | +}: { |
| 29 | + error: unknown; |
| 30 | + type?: string; |
| 31 | + context?: Properties; |
| 32 | + forceSendInDev?: boolean; |
| 33 | +}): void => { |
| 34 | + if (process.env.NODE_ENV === "development" && forceSendInDev !== true) { |
| 35 | + console.error(error); |
| 36 | + } else { |
| 37 | + doInitPostHog(); |
| 38 | + type = type || "Internal Error"; |
| 39 | + const slugType = type.replaceAll(NON_WORD, "-").toLowerCase(); |
| 40 | + context = { |
| 41 | + type, |
| 42 | + ...(context || {}), |
| 43 | + }; |
| 44 | + |
| 45 | + if (typeof error === "string") { |
| 46 | + error = new Error(error); |
| 47 | + } else if (!(error instanceof Error)) { |
| 48 | + try { |
| 49 | + const serialized = JSON.stringify(error); |
| 50 | + error = new Error(serialized); |
| 51 | + } catch { |
| 52 | + error = new Error(typeof error); |
| 53 | + } |
| 54 | + } |
| 55 | + posthog.captureException(error, { ...context, type: slugType }); |
| 56 | + if (process.env.NODE_ENV === "development") console.error(error); |
| 57 | + } |
| 58 | +}; |
| 59 | + |
| 60 | +export default internalError; |
0 commit comments