Logging Custom Error Fields with Rollbar and react-rollbar

Rollbar is a popular error monitoring service with solid React support via the react-rollbar package. Out of the box it captures exceptions and stack traces, but sometimes you need to surface custom fields from your own error classes. Here’s how to do it for unhandled errors caught by ErrorBoundary.

Setup

Install the packages:

npm install rollbar react-rollbar

Wrap your app with RollbarProvider:

import { RollbarProvider } from '@rollbar/react';

const rollbarConfig = {
  accessToken: 'YOUR_CLIENT_ACCESS_TOKEN',
  environment: 'production',
};

function App() {
  return (
    <RollbarProvider config={rollbarConfig}>
      <YourApp />
    </RollbarProvider>
  );
}

Custom Error Class

Define a custom error class that carries the extra fields you want to report:

// errors/UnknownError.js
export default class UnknownError extends Error {
  constructor(errorCode, message) {
    super(message);

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, UnknownError);
    }

    this.name = 'UnknownError';
    this.errorCode = errorCode;
  }
}

Throw it anywhere in your component tree:

throw new UnknownError('PAYMENT_FAILED', 'Payment could not be processed');

Extracting Custom Fields with extra

The extra prop on ErrorBoundary accepts either a plain object or a function that receives the caught error and returns an object. This is the key to pulling fields off your custom error class:

import { ErrorBoundary } from '@rollbar/react';
import FallbackUI from './FallbackUI';

function AppBoundary({ children }) {
  return (
    <ErrorBoundary
      fallbackUI={FallbackUI}
      extra={err => ({
        email: err.email,
        errorCode: err.errorCode,
      })}
    >
      {children}
    </ErrorBoundary>
  );
}

When UnknownError is thrown, Rollbar will log the error with errorCode visible under the Custom tab in the dashboard. Fields that are undefined on a given error (e.g. a plain Error that has no errorCode) are simply omitted — so this pattern is safe to use as a top-level boundary for all error types.

More details in the official docs: Rollbar Browser JS Reference and rollbar-react.