Error Tracking and Instrumentation
Set up error tracking in a Next.js application by instrumenting the code to catch and report runtime exceptions or other errors.
import Sentry from '@sentry/nextjs';
const SENTRY_DSN = process.env.SENTRY_DSN;
// Initialize Sentry
Sentry.init({ dsn: SENTRY_DSN });
Initializes Sentry with a DSN from your environment variables for error tracking.
import * as Sentry from '@sentry/nextjs';
export function reportError(error) {
Sentry.captureException(error);
}
Defines a function to report errors manually to Sentry.
import { useEffect } from 'react';
import { reportError } from './errorReporting';
function MyApp({ Component, pageProps }) {
useEffect(() => {
const handleError = (event) => {
reportError(event.error);
};
window.addEventListener('error', handleError);
return () => window.removeEventListener('error', handleError);
}, []);
return <Component {...pageProps} />;
}
export default MyApp;
Sets up a global error handler in a Next.js application component to catch and report runtime exceptions using the previously defined reportError function.