Skip to content

Instantly share code, notes, and snippets.

@Froelund
Last active November 30, 2023 04:35
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Froelund/4d04d94931fa81a245a7dba8fc90e68a to your computer and use it in GitHub Desktop.
Save Froelund/4d04d94931fa81a245a7dba8fc90e68a to your computer and use it in GitHub Desktop.
Next.js Typescript error reporting
import { captureException, flush } from '@sentry/nextjs';
import NextErrorComponent from 'next/error';
import type { ErrorProps } from 'next/error';
import type { NextPage } from 'next';
interface AppErrorProps extends ErrorProps {
err?: Error;
hasGetInitialPropsRun?: boolean;
}
const AppError: NextPage<AppErrorProps> = ({
hasGetInitialPropsRun,
err,
statusCode,
}) => {
if (!hasGetInitialPropsRun && err) {
captureException(err);
}
return <NextErrorComponent statusCode={statusCode} />;
};
AppError.getInitialProps = async (ctx) => {
const errorInitialProps: AppErrorProps =
await NextErrorComponent.getInitialProps(ctx);
errorInitialProps.hasGetInitialPropsRun = true;
if (ctx.err) {
captureException(ctx.err);
await flush(2000);
return errorInitialProps;
}
captureException(
new Error(`_error.tsx getInitialProps missing data at path: ${ctx.asPath}`)
);
await flush(2000);
return errorInitialProps;
};
export default AppError;
@cezarsmpio
Copy link

Thanks!

@svict4
Copy link

svict4 commented Sep 2, 2021

Thanks very much!

@thucpn
Copy link

thucpn commented Jan 24, 2022

Thanks!

@shehi
Copy link

shehi commented May 11, 2022

Indeed, thanks!

@cendenta
Copy link

Yes, thank you very much!

@yves0003
Copy link

yves0003 commented Jun 1, 2022

thks 👍

@LucasMatuszewski
Copy link

Thanks a lot! I have come to an almost identical solution but haven't figured out to make hasGetInitialPropsRun and err optional... Sometimes the solution is so close... You saved me a lot of time :)

@chrillep
Copy link

@ramonfabrega
Copy link

// _error.tsx
import type { NextPage } from "next";

import NextErrorComponent from "next/error";
import type { ErrorProps } from "next/error";

import * as Sentry from "@sentry/nextjs";

const CustomErrorComponent: NextPage<ErrorProps> = ({ statusCode }) => {
  return <NextErrorComponent statusCode={statusCode} />;
};

CustomErrorComponent.getInitialProps = async (context) => {
  await Sentry.captureUnderscoreErrorException(context);

  return NextErrorComponent.getInitialProps(context);
};

export default CustomErrorComponent;

@brun0xff
Copy link

thank you, man ❤️

@StasNemy
Copy link

Thanks a lot🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment