try-error Documentation
Configuration Reference
Configure try-error behavior and customize error handling for your application
💡 Do I need to configure try-error?
Short answer: No! try-error works perfectly out of the box without any configuration.
Configuration is optional and only needed when you want to:
- • Optimize performance for production (disable stack traces, etc.)
- • Set up error monitoring and reporting
- • Customize error behavior for your specific needs
- • Use environment-specific settings
Getting started? Just import and use trySync()
, tryAsync()
, and createTryError()
directly. Come back here when you need customization!
Quick Setup (Recommended)
Use our one-liner setup utilities for instant optimization with sensible defaults. These functions automatically configure try-error for your environment.
⚡ Environment-Specific Setup
1// Import setup utilities (tree-shakeable)
2import { setupNode, setupReact, setupNextJs, autoSetup } from 'try-error/setup';
3
4// Node.js/Express - Automatic environment detection
5setupNode(); // ✨ Optimized for dev/prod automatically
6
7// React/Vite - Browser-optimized configuration
8setupReact(); // ✨ Perfect for client-side apps
9
10// Next.js - Handles both SSR and client-side
11setupNextJs(); // ✨ Works for both server and client
12
13// Auto-detect environment (works everywhere)
14autoSetup(); // ✨ Detects Node.js, React, Next.js, etc.
15
16// High-performance (for critical applications)
17import { setupPerformance } from 'try-error/setup';
18setupPerformance(); // ✨ Maximum performance, minimal overhead
19
20// Testing environment
21import { setupTesting } from 'try-error/setup';
22setupTesting(); // ✨ Test-friendly configuration
🎯 Benefits of Quick Setup
- • Zero boilerplate: One line replaces 20+ lines of configuration
- • Environment-aware: Automatically optimizes for dev/prod/test
- • Best practices: Includes performance optimizations by default
- • Tree-shakeable: Only includes what you use
🔍 What happens under the hood?
Here's exactly what each setup function does when you call it:
setupNode()
1// Equivalent manual configuration:
2configure({
3 captureStackTrace: process.env.NODE_ENV !== 'production',
4 stackTraceLimit: process.env.NODE_ENV === 'production' ? 5 : 50,
5 developmentMode: process.env.NODE_ENV === 'development',
6
7 onError: (error) => {
8 if (process.env.NODE_ENV === 'production') {
9 // Minimal production logging
10 console.error(`[ERROR] ${error.type}: ${error.message}`);
11 } else {
12 // Detailed development logging
13 console.group(`🚨 TryError: ${error.type}`);
14 console.error('Message:', error.message);
15 console.error('Context:', error.context);
16 console.error('Stack:', error.stack);
17 console.groupEnd();
18 }
19 return error;
20 },
21
22 serializer: (error) => ({
23 type: error.type,
24 message: error.message,
25 timestamp: error.timestamp,
26 ...(process.env.NODE_ENV === 'development' && {
27 context: error.context,
28 stack: error.stack
29 })
30 })
31});
setupReact()
1// Equivalent manual configuration:
2configure({
3 captureStackTrace: import.meta.env.DEV, // Vite
4 stackTraceLimit: import.meta.env.PROD ? 3 : 20,
5 developmentMode: import.meta.env.DEV,
6
7 onError: (error) => {
8 if (import.meta.env.PROD) {
9 // Send to analytics in production
10 window.gtag?.('event', 'exception', {
11 description: `${error.type}: ${error.message}`,
12 fatal: false
13 });
14 } else {
15 // Development console logging
16 console.group(`🚨 TryError: ${error.type}`);
17 console.error('Message:', error.message);
18 console.error('Context:', error.context);
19 console.groupEnd();
20 }
21 return error;
22 },
23
24 serializer: (error) => ({
25 type: error.type,
26 message: error.message,
27 url: window.location.href,
28 userAgent: navigator.userAgent,
29 timestamp: error.timestamp
30 })
31});
setupPerformance()
1// Equivalent manual configuration:
2configure({
3 captureStackTrace: false, // Disabled for max performance
4 stackTraceLimit: 0, // No stack traces
5 developmentMode: false, // Production mode
6
7 onError: (error) => {
8 // Minimal logging only
9 console.error(`Error: ${error.type}`);
10 return error;
11 },
12
13 serializer: (error) => ({
14 type: error.type,
15 message: error.message,
16 timestamp: error.timestamp
17 // No context or stack for performance
18 })
19});
20
21// Also configures performance optimizations:
22configurePerformance({
23 errorCreation: {
24 cacheConstructors: true,
25 lazyStackTrace: true,
26 objectPooling: true,
27 poolSize: 100
28 },
29 contextCapture: {
30 maxContextSize: 1024 * 5, // 5KB limit
31 deepClone: false,
32 timeout: 50
33 },
34 memory: {
35 maxErrorHistory: 50,
36 useWeakRefs: true,
37 gcHints: true
38 }
39});
Setup with Custom Options
All setup functions accept custom options to override defaults.
1// Setup with custom error reporting
2setupNode({
3 onError: (error) => {
4 // Send to your monitoring service
5 sendToSentry(error);
6 sendToDatadog(error);
7 return error;
8 }
9});
10
11// React setup with analytics
12setupReact({
13 onError: (error) => {
14 // Send to analytics
15 gtag('event', 'exception', {
16 description: `${error.type}: ${error.message}`,
17 fatal: false
18 });
19 return error;
20 }
21});
22
23// Next.js with custom serialization
24setupNextJs({
25 serializer: (error) => ({
26 type: error.type,
27 message: error.message,
28 url: typeof window !== 'undefined' ? window.location.href : 'server',
29 timestamp: error.timestamp
30 })
31});
Custom Setup Function
Create your own setup function with organizational defaults.
1import { createCustomSetup } from 'try-error/setup';
2
3// Create your organization's standard setup
4const setupMyApp = createCustomSetup({
5 onError: (error) => sendToMyMonitoringService(error),
6 serializer: (error) => myCustomSerializer(error),
7 captureStackTrace: process.env.NODE_ENV !== 'production'
8});
9
10// Use in your applications
11setupMyApp(); // Uses your defaults
12setupMyApp({ developmentMode: true }); // Override specific options
Manual Configuration Guide
Want complete control? Here's how to configure try-error manually with all available options.
💡 When to use manual configuration
- • You need very specific behavior not covered by setup utilities
- • You're integrating with custom monitoring/logging systems
- • You want to understand exactly what's happening
- • You're building a library that uses try-error internally
Complete Configuration Interface
1interface TryErrorConfig {
2 /**
3 * Whether to capture stack traces (expensive operation)
4 * @default true in development, false in production
5 */
6 captureStackTrace?: boolean;
7
8 /**
9 * Maximum stack trace depth to capture
10 * @default 10
11 */
12 stackTraceLimit?: number;
13
14 /**
15 * Include source location in errors
16 * @default true
17 */
18 includeSource?: boolean;
19
20 /**
21 * Default error type for untyped errors
22 * @default "Error"
23 */
24 defaultErrorType?: string;
25
26 /**
27 * Enable development mode features (verbose logging, etc.)
28 * @default false
29 */
30 developmentMode?: boolean;
31
32 /**
33 * Custom error serialization function
34 * Called when converting errors to JSON or for logging
35 */
36 serializer?: (error: TryError) => Record<string, unknown>;
37
38 /**
39 * Global error transformation hook
40 * Called for every error created, allows modification
41 */
42 onError?: (error: TryError) => TryError;
43}
Step-by-Step Manual Setup
1import { configure } from 'try-error';
2
3// Step 1: Basic configuration
4configure({
5 // Performance settings
6 captureStackTrace: process.env.NODE_ENV !== 'production',
7 stackTraceLimit: process.env.NODE_ENV === 'production' ? 5 : 50,
8 includeSource: true,
9
10 // Behavior settings
11 defaultErrorType: 'ApplicationError',
12 developmentMode: process.env.NODE_ENV === 'development',
13
14 // Custom serialization for logging/monitoring
15 serializer: (error) => {
16 const base = {
17 type: error.type,
18 message: error.message,
19 timestamp: error.timestamp,
20 source: error.source
21 };
22
23 // Include sensitive data only in development
24 if (process.env.NODE_ENV === 'development') {
25 return {
26 ...base,
27 context: error.context,
28 stack: error.stack,
29 cause: error.cause
30 };
31 }
32
33 // Production: minimal data
34 return base;
35 },
36
37 // Global error handling
38 onError: (error) => {
39 // Log to console
40 if (process.env.NODE_ENV === 'development') {
41 console.group(`🚨 ${error.type}`);
42 console.error('Message:', error.message);
43 console.error('Context:', error.context);
44 console.error('Stack:', error.stack);
45 console.groupEnd();
46 } else {
47 console.error(`[${error.type}] ${error.message}`);
48 }
49
50 // Send to monitoring services
51 if (process.env.NODE_ENV === 'production') {
52 // Example integrations
53 sendToSentry(error);
54 sendToDatadog(error);
55 sendToNewRelic(error);
56 }
57
58 // Analytics tracking
59 if (typeof window !== 'undefined' && window.gtag) {
60 window.gtag('event', 'exception', {
61 description: `${error.type}: ${error.message}`,
62 fatal: false
63 });
64 }
65
66 // Must return the error (can be modified)
67 return error;
68 }
69});
Configuration Option Details
captureStackTrace
Controls whether stack traces are captured when errors are created.
- • true: Full stack traces (useful for debugging)
- • false: No stack traces (better performance)
- • Recommendation: true in development, false in production
stackTraceLimit
Maximum number of stack frames to capture.
- • Higher values: More detailed traces, slower performance
- • Lower values: Less detail, better performance
- • Recommendation: 50 in development, 5 in production
serializer
Function that converts TryError objects to plain objects for logging/JSON.
1serializer: (error) => ({
2 // Always include these
3 type: error.type,
4 message: error.message,
5 timestamp: error.timestamp,
6
7 // Conditional fields
8 ...(error.context && { context: error.context }),
9 ...(error.source && { source: error.source }),
10 ...(error.stack && { stack: error.stack }),
11
12 // Custom fields
13 severity: getSeverityLevel(error.type),
14 userId: getCurrentUserId(),
15 sessionId: getSessionId()
16})
onError
Global hook called for every error. Use for logging, monitoring, and analytics.
1onError: (error) => {
2 // Rate limiting to prevent spam
3 if (shouldRateLimit(error.type)) {
4 return error;
5 }
6
7 // Error categorization
8 const severity = categorizeError(error);
9
10 // Different handling based on severity
11 switch (severity) {
12 case 'critical':
13 sendToSlack(error);
14 sendToSentry(error);
15 break;
16 case 'warning':
17 sendToSentry(error);
18 break;
19 case 'info':
20 logToFile(error);
21 break;
22 }
23
24 // Enrich error with additional context
25 return {
26 ...error,
27 context: {
28 ...error.context,
29 severity,
30 environment: process.env.NODE_ENV,
31 version: process.env.APP_VERSION
32 }
33 };
34}
Configuration API
For advanced use cases, you can use the configuration API directly to customize try-error behavior.
configure()
Configure global settings for try-error behavior.
1import { configure, TryErrorConfig } from 'try-error';
2
3// Configure global settings
4configure({
5 // Enable/disable stack trace capture
6 captureStackTrace: true,
7
8 // Maximum stack trace depth
9 stackTraceLimit: 10,
10
11 // Include source location in errors
12 includeSource: true,
13
14 // Default error type for untyped errors
15 defaultErrorType: 'Error',
16
17 // Enable development mode features
18 developmentMode: process.env.NODE_ENV === 'development',
19
20 // Custom error serialization
21 serializer: (error) => ({
22 type: error.type,
23 message: error.message,
24 timestamp: error.timestamp,
25 ...(process.env.NODE_ENV === 'development' && {
26 stack: error.stack,
27 context: error.context
28 })
29 }),
30
31 // Error transformation hook
32 onError: (error) => {
33 // Log to monitoring service
34 if (process.env.NODE_ENV === 'production') {
35 logToMonitoring(error);
36 }
37 return error;
38 }
39});
40
41// Or use a preset
42configure('production'); // Uses ConfigPresets.production()
43configure('development'); // Uses ConfigPresets.development()
Configuration Presets
Pre-built configurations for common environments.
1import { ConfigPresets, configure } from 'try-error';
2
3// Use built-in presets
4configure(ConfigPresets.development()); // Full debugging features
5configure(ConfigPresets.production()); // Performance optimized
6configure(ConfigPresets.test()); // Test-friendly configuration
7configure(ConfigPresets.performance()); // Maximum performance
8
9// Customize presets
10const customConfig = {
11 ...ConfigPresets.production(),
12 onError: (error) => sendToMyService(error)
13};
14configure(customConfig);
15
16// Environment-based configuration
17import { createEnvConfig } from 'try-error';
18
19configure(createEnvConfig({
20 development: ConfigPresets.development(),
21 production: ConfigPresets.production(),
22 test: ConfigPresets.test()
23}));
Scoped Configuration
Create isolated configurations that don't affect global state.
1import { createScope } from 'try-error';
2
3// Create a scoped configuration
4const { config, createError } = createScope({
5 captureStackTrace: false,
6 defaultErrorType: 'CustomError',
7 onError: (error) => {
8 console.log('Scoped error:', error.message);
9 return error;
10 }
11});
12
13// Use scoped error creation
14const error = await createError({
15 message: 'This uses scoped config',
16 context: { scope: 'isolated' }
17});
18
19// Global config remains unchanged
20const globalError = createTryError('GlobalError', 'Uses global config');
Configuration Options
Complete reference for all configuration options available in try-error.
TryErrorConfig Interface
1interface TryErrorConfig {
2 /**
3 * Whether to capture stack traces (expensive operation)
4 * @default true in development, false in production
5 */
6 captureStackTrace?: boolean;
7
8 /**
9 * Maximum stack trace depth to capture
10 * @default 10
11 */
12 stackTraceLimit?: number;
13
14 /**
15 * Include source location in errors
16 * @default true
17 */
18 includeSource?: boolean;
19
20 /**
21 * Default error type for untyped errors
22 * @default "Error"
23 */
24 defaultErrorType?: string;
25
26 /**
27 * Enable development mode features (verbose logging, etc.)
28 * @default false
29 */
30 developmentMode?: boolean;
31
32 /**
33 * Custom error serialization function
34 */
35 serializer?: (error: TryError) => Record<string, unknown>;
36
37 /**
38 * Global error transformation hook
39 */
40 onError?: (error: TryError) => TryError;
41}
Performance Configuration
Advanced performance optimization settings for high-throughput applications.
1interface PerformanceConfig {
2 /**
3 * Error creation optimization settings
4 */
5 errorCreation?: {
6 /**
7 * Cache error constructors for reuse
8 * @default false
9 */
10 cacheConstructors?: boolean;
11
12 /**
13 * Only capture stack trace when accessed (lazy)
14 * @default false
15 */
16 lazyStackTrace?: boolean;
17
18 /**
19 * Enable experimental object pooling
20 * @default false
21 */
22 objectPooling?: boolean;
23
24 /**
25 * Object pool size when pooling is enabled
26 * @default 50
27 */
28 poolSize?: number;
29 };
30
31 /**
32 * Context capture optimization settings
33 */
34 contextCapture?: {
35 /**
36 * Maximum context size in bytes
37 * @default 10240 (10KB)
38 */
39 maxContextSize?: number;
40
41 /**
42 * Whether to deep clone context objects
43 * @default true
44 */
45 deepClone?: boolean;
46
47 /**
48 * Timeout for async context capture in milliseconds
49 * @default 100
50 */
51 timeout?: number;
52 };
53
54 /**
55 * Memory management settings
56 */
57 memory?: {
58 /**
59 * Maximum number of errors to keep in history
60 * @default 100
61 */
62 maxErrorHistory?: number;
63
64 /**
65 * Use weak references for large contexts
66 * @default false
67 */
68 useWeakRefs?: boolean;
69
70 /**
71 * Provide garbage collection hints
72 * @default false
73 */
74 gcHints?: boolean;
75 };
76}
Environment-Specific Configuration
Configure different behaviors for development, testing, and production environments.
Development Configuration
1// config/development.ts
2import { configure } from 'try-error';
3
4configure({
5 captureStackTrace: true,
6 stackTraceLimit: 50, // More detailed stack traces
7 includeSource: true,
8 developmentMode: true,
9
10 serializer: (error) => ({
11 type: error.type,
12 message: error.message,
13 stack: error.stack,
14 source: error.source,
15 context: error.context,
16 timestamp: error.timestamp,
17 cause: error.cause
18 }),
19
20 onError: (error) => {
21 // Detailed console logging in development
22 console.group(`🚨 TryError: ${error.type}`);
23 console.error('Message:', error.message);
24 console.error('Source:', error.source);
25 console.error('Context:', error.context);
26 console.error('Stack:', error.stack);
27 console.groupEnd();
28 return error;
29 }
30});
Production Configuration
1// config/production.ts
2import { configure } from 'try-error';
3
4configure({
5 captureStackTrace: false, // Disable for performance
6 stackTraceLimit: 5,
7 includeSource: false, // Don't expose source paths
8 developmentMode: false,
9
10 serializer: (error) => ({
11 type: error.type,
12 message: error.message,
13 timestamp: error.timestamp,
14 // Don't include sensitive information
15 }),
16
17 onError: (error) => {
18 // Send to monitoring service
19 sendToSentry(error);
20 sendToDatadog(error);
21
22 // Log minimal information
23 console.error(`Error: ${error.type} - ${error.message}`);
24 return error;
25 }
26});
Testing Configuration
1// config/testing.ts
2import { configure } from 'try-error';
3
4// Collect errors for test assertions
5const testErrors: TryError[] = [];
6
7configure({
8 captureStackTrace: true,
9 stackTraceLimit: 10,
10 includeSource: true,
11 developmentMode: true,
12
13 serializer: (error) => ({
14 type: error.type,
15 message: error.message,
16 context: error.context,
17 source: error.source,
18 stack: error.stack
19 }),
20
21 onError: (error) => {
22 testErrors.push(error);
23 return error;
24 }
25});
26
27// Helper for tests
28export function getTestErrors(): TryError[] {
29 return [...testErrors];
30}
31
32export function clearTestErrors(): void {
33 testErrors.length = 0;
34}
Performance Optimization
Advanced configuration for high-performance applications.
High-Performance Configuration
1import { configure, ConfigPresets } from 'try-error';
2
3// Use the performance preset
4configure(ConfigPresets.performance());
5
6// Or configure manually
7configure({
8 captureStackTrace: false,
9 stackTraceLimit: 0,
10 includeSource: false,
11 developmentMode: false,
12
13 // Performance optimizations
14 performance: {
15 errorCreation: {
16 cacheConstructors: true,
17 lazyStackTrace: true,
18 objectPooling: true,
19 poolSize: 100
20 },
21 contextCapture: {
22 maxContextSize: 1024 * 5, // 5KB limit
23 deepClone: false,
24 timeout: 50
25 },
26 memory: {
27 maxErrorHistory: 50,
28 useWeakRefs: true,
29 gcHints: true
30 }
31 }
32});
Performance Monitoring
1import { Performance } from 'try-error';
2
3// Measure error creation performance
4const metrics = Performance.measureErrorCreation(1000);
5console.log(`Average error creation time: ${metrics.averageTime}ms`);
6
7// Monitor memory usage (Node.js only)
8const memoryUsage = Performance.getMemoryUsage();
9if (memoryUsage) {
10 console.log('Memory usage:', memoryUsage);
11}
12
13// Set up performance monitoring
14configure({
15 onError: (error) => {
16 // Track error creation time
17 const creationTime = Date.now() - error.timestamp;
18 if (creationTime > 10) { // Log slow error creation
19 console.warn(`Slow error creation: ${creationTime}ms for ${error.type}`);
20 }
21 return error;
22 }
23});
Configuration Best Practices
✅ Do
- • Use setup utilities for quick, optimized configuration
- • Configure try-error early in your application startup
- • Use environment-specific configurations
- • Disable stack traces in production for performance
- • Set up error monitoring and reporting
- • Use scoped configurations for isolated components
- • Test your error handling configuration
❌ Don't
- • Configure try-error multiple times in the same application
- • Include sensitive data in error contexts
- • Use development configuration in production
- • Ignore performance implications of stack trace capture
- • Set overly large context size limits
- • Forget to handle errors in your onError hook
Related Pages
Performance Guide
Detailed performance optimization strategies and implementation examples
View Performance Guide →