npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-catch-error

v1.0.0

Published

A robust error handling utility for JavaScript and TypeScript applications with retry, timeout, and logging capabilities

Readme

React Catch Error

A robust error handling utility for JavaScript and TypeScript applications with retry, timeout, and logging capabilities.

Installation

bun add react-catch-error
# or
npm install react-catch-error
# or
yarn add react-catch-error

Features

  • Unified error handling for both async and sync functions
  • Detailed error results with execution metadata
  • Configurable retry mechanism with delay and conditional retry
  • Timeout support for async operations
  • Flexible error logging with custom formatters
  • TypeScript support with full type safety

Basic Usage

Handling Async Operations

import { catchError } from 'react-catch-error';

// Basic usage with async/await
async function fetchUserData(userId: string) {
  const { data, error, meta } = await catchError(
    async () => {
      const response = await fetch(`/api/users/${userId}`);
      if (!response.ok) throw new Error(`Failed to fetch user: ${response.statusText}`);
      return response.json();
    }
  );

  if (error) {
    console.error('Error fetching user:', error.message);
    return null;
  }

  console.log(`Fetched user in ${meta.executionTime}ms`);
  return data;
}

Handling Sync Operations

import { catchErrorSync } from 'react-catch-error';

function parseConfig(configStr: string) {
  const { data, error } = catchErrorSync(() => {
    return JSON.parse(configStr);
  });

  if (error) {
    console.error('Invalid config format:', error.message);
    return {};
  }

  return data;
}

Advanced Features

Retry Mechanism

const { data, error, meta } = await catchError(
  async () => fetchFromUnreliableAPI(),
  {
    retry: {
      attempts: 3,                       // Try up to 3 times
      delay: 1000,                       // Wait 1 second between attempts
      onProgress: ({ attempt, maxAttempts, error }) => {
        console.log(`Attempt ${attempt}/${maxAttempts} failed with: ${error.message}`);
      }
    }
  }
);

if (meta.retryCount) {
  console.log(`Operation succeeded after ${meta.retryCount} retries`);
}

Timeout Support

const { data, error, meta } = await catchError(
  async () => fetchData(),
  {
    timeout: 5000,  // Set 5-second timeout
  }
);

if (error && meta.isTimeout) {
  console.error('Operation timed out');
}

Custom Error Logging

import { setDefaultCatchErrorOptions } from 'react-catch-error';

// Global settings
setDefaultCatchErrorOptions({
  logOnError: true,
  logErrorSeverity: 'warn'
});

// Per-function custom logging
const result = await catchError(
  async () => apiCall(),
  {
    logOnError: (params) => ({
      message: `API Error: ${params.error.message}`,
      statusCode: (params.error as any).statusCode,
      timestamp: new Date().toISOString(),
      attempt: params.attempt
    }),
    logErrorSeverity: 'error'
  }
);

API Reference

Core Functions

  • catchError<TData, TResult = TData, E extends Error = Error>(promiseFn: () => Promise<TData>, options?: CatchErrorOptions<E>): Promise<ErrorResult<TResult, E>>
  • catchErrorSync<T, E extends Error = Error>(fn: () => T, options?: CatchErrorOptions<E>): ErrorResult<T, E>
  • setDefaultCatchErrorOptions(options: Partial<CatchErrorOptions>): void
  • normalizeError(errorValue: unknown): Error

Types

ErrorResult<T, E extends Error = Error>

The result object returned by both catchError and catchErrorSync:

type ErrorResult<T, E extends Error = Error> = {
  data?: T;                 // Result data (if successful)
  error?: E | TimeoutError; // Error object (if failed)
  meta: {
    executionTime: number;  // Total execution time in ms
    retryCount?: number;    // Number of retries performed
    retryErrors?: (E | TimeoutError)[]; // Array of errors from each retry
    isTimeout?: boolean;    // Whether a timeout occurred
    [key: string]: unknown; // Additional custom metadata
  };
};

CatchErrorOptions

Configuration options for error handling:

type CatchErrorOptions<E extends Error = Error> = {
  logger?: Logger;  // Custom logger instance
  logOnError?: boolean | string | ((params: LogOnErrorFormatterParams<E>) => LogOnErrorFormatterResult);
  logErrorSeverity?: "error" | "warn" | "info" | "debug";
  retry?: {
    attempts: number;
    delay?: number | ((attempt: number, error: E | TimeoutError) => number);
    retryIf?: (error: E | TimeoutError) => boolean;
    onProgress?: (progress: { attempt: number; maxAttempts: number; error: E | TimeoutError }) => void;
  };
  timeout?: number;
  onFinally?: () => void;
};

License

MIT