react-catch-error
v1.0.0
Published
A robust error handling utility for JavaScript and TypeScript applications with retry, timeout, and logging capabilities
Maintainers
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-errorFeatures
- 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>): voidnormalizeError(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
