peppa/apps/web/components/ErrorReporter.tsx
2026-11-16 10:07:26 +05:00

70 lines
3.2 KiB
TypeScript

"use client";
import { useEffect } from "react";
const MAX_PER_PAGE = 10;
// PEP-137: what the page writes to console.error (a hydration mismatch, a React warning that the
// dev overlay shows as «1 Issue») never reaches window.onerror. The wrapper is installed when
// this module loads — before hydration — and keeps the first messages until the reporter mounts.
const consoleErrors: Array<{ message: string; stack?: string }> = [];
let onConsoleError: ((e: { message: string; stack?: string }) => void) | null = null;
if (typeof window !== "undefined" && !(window as { __peppaConsoleWrapped?: boolean }).__peppaConsoleWrapped) {
(window as { __peppaConsoleWrapped?: boolean }).__peppaConsoleWrapped = true;
const original = console.error.bind(console);
console.error = (...args: unknown[]) => {
original(...args);
try {
const err = args.find((a): a is Error => a instanceof Error);
const message = args
.map((a) => (a instanceof Error ? a.message : typeof a === "string" ? a : JSON.stringify(a) ?? ""))
.join(" ")
.replace(/%[sdoc]/g, "")
.trim();
if (!message) return;
const entry = { message, stack: err?.stack };
if (onConsoleError) onConsoleError(entry);
else if (consoleErrors.length < MAX_PER_PAGE) consoleErrors.push(entry);
} catch {
/* reporting must never break the page */
}
};
}
/** PEP-91: browser errors of Peppa's own pages → /api/client-errors → Bugsink (PEP-web). */
export function ErrorReporter() {
useEffect(() => {
let sent = 0;
const seen = new Set<string>();
const send = (type: string, message: string, stack?: string) => {
const key = `${type}|${message}`;
if (sent >= MAX_PER_PAGE || seen.has(key) || !message) return;
seen.add(key);
sent++;
const body = JSON.stringify({ type, message: message.slice(0, 2000), stack: stack?.slice(0, 8000), url: location.pathname + location.search });
void fetch("/api/client-errors", { method: "POST", headers: { "Content-Type": "application/json" }, body, keepalive: true }).catch(() => {});
};
const onError = (ev: ErrorEvent) => {
const e = ev.error as Error | undefined;
// "Script error." comes from cross-origin scripts without details: nothing to act on.
if (!e && (!ev.message || ev.message === "Script error.")) return;
send(e?.name ?? "Error", e?.message ?? ev.message, e?.stack ?? (ev.filename ? ` at ${ev.filename}:${ev.lineno}:${ev.colno}` : undefined));
};
const onRejection = (ev: PromiseRejectionEvent) => {
const r = ev.reason as Error | string | undefined;
if (r instanceof Error) send(r.name, r.message, r.stack);
else send("UnhandledRejection", typeof r === "string" ? r : JSON.stringify(r) ?? "");
};
onConsoleError = (e) => send("ConsoleError", e.message, e.stack);
for (const e of consoleErrors.splice(0)) onConsoleError(e);
window.addEventListener("error", onError);
window.addEventListener("unhandledrejection", onRejection);
return () => {
onConsoleError = null;
window.removeEventListener("error", onError);
window.removeEventListener("unhandledrejection", onRejection);
};
}, []);
return null;
}