| 9e346cc | | | 1 | "use client"; |
| 9e346cc | | | 2 | |
| 9e346cc | | | 3 | import { useEffect } from "react"; |
| 9e346cc | | | 4 | |
| 9e346cc | | | 5 | export function DevErrorReporter() { |
| 9e346cc | | | 6 | useEffect(() => { |
| 9e346cc | | | 7 | if (process.env.NODE_ENV === "production") return; |
| 9e346cc | | | 8 | |
| 9e346cc | | | 9 | const originalError = console.error; |
| 9e346cc | | | 10 | const originalWarn = console.warn; |
| 9e346cc | | | 11 | |
| 9e346cc | | | 12 | function report(type: string, args: unknown[]) { |
| 9e346cc | | | 13 | const message = args |
| 9e346cc | | | 14 | .map((a) => (typeof a === "string" ? a : JSON.stringify(a, null, 2))) |
| 9e346cc | | | 15 | .join(" ") |
| 9e346cc | | | 16 | .slice(0, 4000); |
| 9e346cc | | | 17 | |
| 9e346cc | | | 18 | fetch("/api/dev-errors", { |
| 9e346cc | | | 19 | method: "POST", |
| 9e346cc | | | 20 | headers: { "Content-Type": "application/json" }, |
| 9e346cc | | | 21 | body: JSON.stringify({ type, message, url: window.location.href }), |
| 9e346cc | | | 22 | }).catch(() => {}); |
| 9e346cc | | | 23 | } |
| 9e346cc | | | 24 | |
| 9e346cc | | | 25 | console.error = (...args: unknown[]) => { |
| 9e346cc | | | 26 | report("console.error", args); |
| 9e346cc | | | 27 | originalError.apply(console, args); |
| 9e346cc | | | 28 | }; |
| 9e346cc | | | 29 | |
| 9e346cc | | | 30 | console.warn = (...args: unknown[]) => { |
| 9e346cc | | | 31 | report("console.warn", args); |
| 9e346cc | | | 32 | originalWarn.apply(console, args); |
| 9e346cc | | | 33 | }; |
| 9e346cc | | | 34 | |
| 9e346cc | | | 35 | const onError = (e: ErrorEvent) => { |
| 9e346cc | | | 36 | report("unhandled-error", [e.message, e.filename, e.lineno, e.colno]); |
| 9e346cc | | | 37 | }; |
| 9e346cc | | | 38 | |
| 9e346cc | | | 39 | const onRejection = (e: PromiseRejectionEvent) => { |
| 9e346cc | | | 40 | report("unhandled-rejection", [String(e.reason)]); |
| 9e346cc | | | 41 | }; |
| 9e346cc | | | 42 | |
| 9e346cc | | | 43 | window.addEventListener("error", onError); |
| 9e346cc | | | 44 | window.addEventListener("unhandledrejection", onRejection); |
| 9e346cc | | | 45 | |
| 9e346cc | | | 46 | return () => { |
| 9e346cc | | | 47 | console.error = originalError; |
| 9e346cc | | | 48 | console.warn = originalWarn; |
| 9e346cc | | | 49 | window.removeEventListener("error", onError); |
| 9e346cc | | | 50 | window.removeEventListener("unhandledrejection", onRejection); |
| 9e346cc | | | 51 | }; |
| 9e346cc | | | 52 | }, []); |
| 9e346cc | | | 53 | |
| 9e346cc | | | 54 | return null; |
| 9e346cc | | | 55 | } |