try-error Documentation
Error Creation API
API reference for creating and working with TryError objects
createTryError
The primary function for creating TryError instances with rich context and metadata.
createTryError Function Signaturetypescript
1function createTryError<T = any>(
2 type: string,
3 message: string,
4 context?: T,
5 cause?: Error | TryError
6): TryError<T>
Parameters
- •
type
- Error classification (e.g., 'ValidationError', 'NetworkError') - •
message
- Human-readable error description - •
context
- Additional error context data (optional) - •
cause
- Original error that caused this error (optional)
Basic Usage
Basic Error Creationtypescript
1import { createTryError } from 'try-error';
2
3// Simple error
4const error = createTryError('ValidationError', 'Email is required');
5
6// Error with context
7const errorWithContext = createTryError(
8 'ValidationError',
9 'Invalid email format',
10 {
11 field: 'email',
12 value: 'invalid-email',
13 rule: 'email_format'
14 }
15);
16
17// Error with cause
18const errorWithCause = createTryError(
19 'NetworkError',
20 'Failed to fetch user data',
21 { userId: '123', url: '/api/users/123' },
22 originalNetworkError
23);
Advanced Context
Rich Error Contexttypescript
1// Complex context with multiple data types
2const complexError = createTryError(
3 'ProcessingError',
4 'Failed to process user registration',
5 {
6 step: 'email_verification',
7 userId: '123',
8 email: 'user@example.com',
9 attempts: 3,
10 lastAttempt: new Date().toISOString(),
11 validationErrors: [
12 { field: 'password', message: 'Too weak' },
13 { field: 'age', message: 'Must be 18+' }
14 ],
15 metadata: {
16 userAgent: 'Mozilla/5.0...',
17 ipAddress: '192.168.1.1',
18 sessionId: 'sess_abc123'
19 }
20 }
21);
22
23// Type-safe context
24interface ValidationContext {
25 field: string;
26 value: unknown;
27 rule: string;
28 expected?: string;
29}
30
31const typedError = createTryError<ValidationContext>(
32 'ValidationError',
33 'Validation failed',
34 {
35 field: 'age',
36 value: 15,
37 rule: 'minimum_age',
38 expected: '18 or older'
39 }
40);
Error Factories
Pre-built factory functions for common error types with consistent structure and context.
Validation Errors
Validation Error Factoriestypescript
1import { createValidationError, createFieldError } from 'try-error';
2
3// Field validation error
4const fieldError = createFieldError('email', 'user@invalid', 'Invalid email format');
5
6// Required field error
7const requiredError = createValidationError('Name is required', {
8 field: 'name',
9 rule: 'required'
10});
11
12// Custom validation error
13const customError = createValidationError('Password too weak', {
14 field: 'password',
15 rule: 'strength',
16 requirements: ['8+ characters', 'uppercase', 'lowercase', 'number'],
17 missing: ['uppercase', 'number']
18});
19
20// Multiple field errors
21const multipleErrors = createValidationError('Multiple validation failures', {
22 fields: [
23 { field: 'email', message: 'Invalid format' },
24 { field: 'age', message: 'Must be 18+' },
25 { field: 'phone', message: 'Invalid phone number' }
26 ]
27});
Network Errors
Network Error Factoriestypescript
1import { createNetworkError, createHttpError, createTimeoutError } from 'try-error';
2
3// HTTP error
4const httpError = createHttpError(404, 'User not found', {
5 url: '/api/users/123',
6 method: 'GET',
7 headers: { 'Authorization': 'Bearer ...' }
8});
9
10// Network timeout
11const timeoutError = createTimeoutError('/api/slow-endpoint', 5000);
12
13// Connection error
14const connectionError = createNetworkError('Connection refused', {
15 host: 'api.example.com',
16 port: 443,
17 protocol: 'https'
18});
19
20// Rate limit error
21const rateLimitError = createHttpError(429, 'Rate limit exceeded', {
22 limit: 100,
23 window: '1h',
24 remaining: 0,
25 resetTime: new Date(Date.now() + 3600000).toISOString()
26});
Authentication & Authorization
Auth Error Factoriestypescript
1import {
2 createAuthError,
3 createPermissionError,
4 createTokenError
5} from 'try-error';
6
7// Authentication error
8const authError = createAuthError('Invalid credentials', {
9 username: 'user@example.com',
10 provider: 'local',
11 attempts: 3
12});
13
14// Token expiration
15const tokenError = createTokenError('Token expired', {
16 tokenType: 'access_token',
17 expiresAt: '2024-01-01T00:00:00Z',
18 issuedAt: '2024-01-01T00:00:00Z'
19});
20
21// Permission error
22const permissionError = createPermissionError('Insufficient permissions', {
23 userId: '123',
24 resource: 'admin_panel',
25 action: 'read',
26 requiredRole: 'admin',
27 userRole: 'user'
28});
29
30// Multi-factor authentication error
31const mfaError = createAuthError('MFA verification required', {
32 userId: '123',
33 mfaMethod: 'totp',
34 challenge: 'mfa_challenge_abc123'
35});
Error Utilities
Utility functions for working with TryError objects, including transformation, serialization, and analysis.
Error Transformation
Error Transformation Utilitiestypescript
1import {
2 enrichError,
3 sanitizeError,
4 transformError,
5 chainError
6} from 'try-error';
7
8// Enrich error with additional context
9const enrichedError = enrichError(originalError, {
10 userId: '123',
11 requestId: 'req_abc123',
12 timestamp: Date.now()
13});
14
15// Sanitize error for client response
16const sanitizedError = sanitizeError(error, {
17 removeFields: ['password', 'token', 'secret'],
18 truncateStrings: 100,
19 includeStack: false
20});
21
22// Transform error type
23const transformedError = transformError(error, {
24 from: 'DatabaseError',
25 to: 'ServiceUnavailableError',
26 message: 'Service temporarily unavailable'
27});
28
29// Chain errors (create error hierarchy)
30const chainedError = chainError(
31 createTryError('ProcessingError', 'Failed to process request'),
32 originalDatabaseError
33);
Error Serialization
Error Serialization Utilitiestypescript
1import {
2 serializeError,
3 deserializeError,
4 toJSON,
5 fromJSON
6} from 'try-error';
7
8// Serialize for logging
9const serialized = serializeError(error, {
10 includeStack: true,
11 includeContext: true,
12 includeSource: true
13});
14
15// Serialize for client response
16const clientSafe = serializeError(error, {
17 includeStack: false,
18 includeContext: false,
19 sanitize: true
20});
21
22// JSON serialization
23const json = toJSON(error);
24const restored = fromJSON(json);
25
26// Custom serialization
27const customSerialized = serializeError(error, {
28 transform: (err) => ({
29 id: generateErrorId(),
30 type: err.type,
31 message: err.message,
32 timestamp: err.timestamp,
33 severity: getSeverity(err.type),
34 category: getCategory(err.type)
35 })
36});
Error Analysis
Error Analysis Utilitiestypescript
1import {
2 isRetryable,
3 getSeverity,
4 getCategory,
5 extractCause,
6 getErrorChain
7} from 'try-error';
8
9// Check if error is retryable
10const canRetry = isRetryable(error);
11
12// Get error severity
13const severity = getSeverity(error); // 'low' | 'medium' | 'high' | 'critical'
14
15// Get error category
16const category = getCategory(error); // 'validation' | 'network' | 'auth' | 'system'
17
18// Extract root cause
19const rootCause = extractCause(error);
20
21// Get full error chain
22const errorChain = getErrorChain(error);
23
24// Error pattern matching
25const isUserError = matchesPattern(error, {
26 types: ['ValidationError', 'AuthenticationError'],
27 severity: ['low', 'medium']
28});
29
30// Error aggregation
31const errorSummary = aggregateErrors([error1, error2, error3], {
32 groupBy: 'type',
33 includeCount: true,
34 includeLatest: true
35});
Error Builders
Fluent builder pattern for creating complex errors with method chaining.
Error Builder Patterntypescript
1import { ErrorBuilder } from 'try-error';
2
3// Fluent error building
4const error = new ErrorBuilder()
5 .type('ValidationError')
6 .message('User registration failed')
7 .context('field', 'email')
8 .context('value', 'invalid-email')
9 .context('rule', 'email_format')
10 .severity('medium')
11 .retryable(false)
12 .cause(originalError)
13 .build();
14
15// Conditional building
16const conditionalError = new ErrorBuilder()
17 .type('ProcessingError')
18 .message('Processing failed')
19 .when(isDevelopment, builder =>
20 builder.context('debug', { stack: true, verbose: true })
21 )
22 .when(isProduction, builder =>
23 builder.context('errorId', generateErrorId())
24 )
25 .build();
26
27// Template-based building
28const templateError = ErrorBuilder
29 .fromTemplate('validation')
30 .field('email')
31 .value('invalid@')
32 .rule('email_format')
33 .build();
34
35// Batch error building
36const errors = ErrorBuilder
37 .batch()
38 .add('ValidationError', 'Email invalid', { field: 'email' })
39 .add('ValidationError', 'Age too low', { field: 'age' })
40 .add('ValidationError', 'Phone invalid', { field: 'phone' })
41 .buildAll();
Best Practices
✅ Do
- • Use consistent error types across your application
- • Include relevant context for debugging
- • Use factory functions for common error patterns
- • Chain errors to preserve error history
- • Sanitize errors before sending to clients
- • Use type-safe context interfaces
❌ Don't
- • Include sensitive data in error context
- • Create overly generic error messages
- • Ignore the original error when chaining
- • Use inconsistent error type naming
- • Include large objects in error context
- • Expose internal system details to users