@heritsilavo/react-error-boundary
TypeScript icon, indicating that this package has built-in type declarations

2.1.3 • Public • Published

@heritsilavo/react-error-boundary

npm version license

A robust error boundary component for React and Next.js applications with customizable error handling and display.

Features

  • 🛡️ Comprehensive error boundary for React and Next.js
  • 🎨 Customizable error display component
  • ⏱️ Auto-hide functionality with progress indicator
  • 🚦 Error context for centralized error management
  • 📦 Supports both CommonJS and ES Modules
  • 🏷️ Fully typed with TypeScript
  • ⚛️ React 18+ compatible
  • ⏭️ Next.js 13+ support

Installation

npm install @heritsilavo/react-error-boundary
# or
yarn add @heritsilavo/react-error-boundary
# or
pnpm add @heritsilavo/react-error-boundary

Peer Dependencies

This package requires:

  • React 18+
  • React DOM 18+
  • For Next.js usage: Next.js 13+

Basic Usage

For React Applications

import { ErrorProvider } from '@heritsilavo/react-error-boundary';

function App() {
  return (
    <ErrorProvider>
      <YourApp />
    </ErrorProvider>
  );
}

For Next.js Applications

import { ErrorProvider } from '@heritsilavo/react-error-boundary/next';

function App({ Component, pageProps }) {
  return (
    <ErrorProvider>
      <Component {...pageProps} />
    </ErrorProvider>
  );
}

Advanced Usage

Custom Error Component

import { ErrorProvider } from '@heritsilavo/react-error-boundary';
import type { ErrorComponentType } from '@heritsilavo/react-error-boundary';

function CustomError({ error, onClose }: ErrorComponentType) {
  return (
    <div className="custom-error">
      <h3>Error: {error.code}</h3>
      <p>{error.message}</p>
      {error.description && <small>{error.description}</small>}
      <button onClick={onClose}>Close</button>
    </div>
  );
}

function App() {
  return (
    <ErrorProvider 
      ErrorComponent={CustomError}
      autoHideDelay={10000}
    >
      <YourApp />
    </ErrorProvider>
  );
}

Throwing Custom Errors

import { useThrowError } from '@heritsilavo/react-error-boundary';

function MyComponent() {
  const throwError = useThrowError();

  const handleClick = () => {
    try {
      // Your code that might fail
    } catch (err) {
      throwError(
        'API_ERROR',
        'Failed to fetch data',
        err.message
      );
    }
  };

  return <button onClick={handleClick}>Fetch Data</button>;
}

Accessing Error Context

import { useError } from '@heritsilavo/react-error-boundary';

function StatusIndicator() {
  const { error, clearError } = useError();

  if (!error) return null;

  return (
    <div>
      <span>Error: {error.message}</span>
      <button onClick={clearError}>Dismiss</button>
    </div>
  );
}

API Reference

Components

ErrorProvider

The root provider component that sets up the error boundary and context.

Props:

Prop Type Default Description
children ReactNode required Your application components
ErrorComponent ComponentType DefaultErrorComponent Custom error display component
autoHideDelay number 5000 Time in ms before auto-hiding (0 to disable)
onError () => void () => {} Callback when error occurs
closeErrorComponetOnClick boolean false Close error component when clicked

ErrorBoundary

The actual error boundary component (used internally by ErrorProvider but can be used directly if needed).

Hooks

useError()

Returns the error context with:

  • error: CustomError | null - Current error object
  • handleError: (error: Error) => void - Function to trigger errors
  • clearError: () => void - Function to clear current error

useThrowError()

Returns a convenience function to throw custom errors: (code: string, message: string, description: string) => void

Types

CustomError

Custom error class with:

  • code: string
  • message: string
  • description: string

ErrorComponentType

Type for custom error components with props:

  • error: CustomError
  • onClose: () => void
  • closeOnClick?: boolean
  • visiblityTime?: number

Styling

The default error component comes with basic styling that can be overridden with CSS variables:

:root {
  --tsila-err-color: #ff4444;
  --tsila-err-bg: #fff;
  --tsila-err-border: 1px solid #ff4444;
  --tsila-err-padding: 1rem;
  --tsila-err-border-radius: 4px;
  --tsila-err-box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

Examples

Handling API Errors

import { useThrowError } from '@heritsilavo/react-error-boundary';

function DataFetcher() {
  const throwError = useThrowError();
  const [data, setData] = useState(null);

  const fetchData = async () => {
    try {
      const response = await fetch('/api/data');
      if (!response.ok) {
        throwError(
          'FETCH_FAILED',
          'Failed to load data',
          `Server returned ${response.status}`
        );
        return;
      }
      setData(await response.json());
    } catch (err) {
      throwError(
        'NETWORK_ERROR',
        'Network request failed',
        err.message
      );
    }
  };

  // ...
}

Custom Error Boundary in Next.js

// pages/_app.tsx
import { ErrorProvider } from '@heritsilavo/react-error-boundary/next';
import { CustomErrorPage } from '../components/CustomErrorPage';

export default function App({ Component, pageProps }) {
  return (
    <ErrorProvider 
      ErrorComponent={CustomErrorPage}
      autoHideDelay={0} // Disable auto-hide
      closeErrorComponetOnClick={true}
    >
      <Component {...pageProps} />
    </ErrorProvider>
  );
}

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

License

ISC © Heritsilavo

Package Sidebar

Install

npm i @heritsilavo/react-error-boundary

Weekly Downloads

0

Version

2.1.3

License

ISC

Unpacked Size

1.88 MB

Total Files

20

Last publish

Collaborators

  • heritsilavo