peppa/apps/web/components/ErrorReporter.tsx
Асель 6e54fc69a6 PEP-91: Peppa reports its own errors to Bugsink — backend to PEP-api, browser to PEP-web
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:39:46 +05:00

40 lines
1.7 KiB
TypeScript

"use client";
import { useEffect } from "react";
const MAX_PER_PAGE = 10;
/** 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) ?? "");
};
window.addEventListener("error", onError);
window.addEventListener("unhandledrejection", onRejection);
return () => {
window.removeEventListener("error", onError);
window.removeEventListener("unhandledrejection", onRejection);
};
}, []);
return null;
}