Blog>
Snippets

Custom Error Handling Middleware

Implement a middleware to catch and handle errors uniformly across your Next.js application.
import { NextApiRequest, NextApiResponse } from 'next';

// An example middleware for custom error handling in a Next.js API route
export const errorHandler = (handler) => async (req, res) => {
  try {
    // Attempt to call the next handler
    await handler(req, res);
  } catch (error) {
    // Handle any error thrown in the middleware chain
    console.error(error);

    // Send a custom error response
    res.status(500).json({ error: 'Internal Server Error' });
  }
};
This is a higher-order function that takes another handler, typically an API route handler, and wraps it with try-catch for error handling. If an error is caught, it logs the error and returns a custom 500 error response.
import { errorHandler } from './middleware/errorHandler';

// Usage of the custom errorHandler middleware in an API route
const myApiHandler = async (req, res) => {
  // Your API logic here
  res.status(200).json({ message: 'Success!' });
};

// Export the wrapped handler with errorHandler middleware
export default errorHandler(myApiHandler);
This is an example usage of the errorHandler middleware created previously. It wraps an API route handler function to ensure any errors it throws are handled by our custom error handling middleware.
import NextErrorComponent from 'next/error'
import * as Sentry from '@sentry/nextjs';

// Override the built-in error page for client-side errors
function MyError({ statusCode, hasGetInitialPropsRun, err }) {
  if (!hasGetInitialPropsRun && err) {
    // Log the error to an error reporting service like Sentry
    Sentry.captureException(err);
  }

  // Render the default Next.js error page with the status code
  return <NextErrorComponent statusCode={statusCode} />;
}

MyError.getInitialProps = async (context) => {
  const errorInitialProps = await NextErrorComponent.getInitialProps(context);

  const { res, err, asPath } = context;

  // Log the error to Sentry
  if (res && res.statusCode === 500 && err) {
    Sentry.captureException(err);
  }

  return { ...errorInitialProps, hasGetInitialPropsRun: true };
};

export default MyError;
This code overrides the default Next.js error page to log server-side errors to Sentry and still display the default error page to the user. It uses the `getInitialProps` method to check if the server-side render of the page errored and captures the exception if so.