@hiennc24/error
v1.0.1
Published
Error package for Node.js and TypeScript with detailed logging and user-friendly messages
Maintainers
Readme
Error Manager Pro
A professional error management package for Node.js and TypeScript applications. Provides clean, detailed error handling with optimized performance, comprehensive logging, and user-friendly error messages.
Features
- 🚀 High Performance: Optimized for production environments
- 🎯 TypeScript First: Full TypeScript support with comprehensive types
- 📝 Professional Logging: Integrated Winston logging with custom configurations
- ✅ Input Validation: Built-in Joi validation with custom error mapping
- 🔒 Rate Limiting: Built-in error rate limiting to prevent spam
- 🎨 User Friendly: Clean error messages for end users
- 📊 Health Monitoring: Built-in health check and performance monitoring
- 🌐 Express Integration: Seamless Express.js middleware support
- 🏗️ Extensible: Easy to extend with custom error types
- 🌍 Multi-Language Support: Professional error messages in 13+ languages
- 🔍 Auto Language Detection: Automatic language detection from HTTP headers
- 🎌 Localization: Localized date, number, and currency formatting
- 📖 Custom Translations: Easy to add custom translations and override defaults
Installation
npm install error-manager-proQuick Start
Basic Usage
import { EnhancedErrorManager, ValidationError, ErrorManagerConfig } from 'error-manager-pro';
// Configure error manager
const config: ErrorManagerConfig = {
environment: 'development',
logLevel: 'error',
includeStack: true,
logToFile: true,
logFilePath: './logs/error.log'
};
const errorManager = new EnhancedErrorManager(config);Express.js Integration
import express from 'express';
import { EnhancedErrorManager, ValidationError } from 'error-manager-pro';
const app = express();
const errorManager = new EnhancedErrorManager({
language: 'en', // Default language
detectLanguageFromHeaders: true, // Auto-detect from Accept-Language
supportedLanguages: ['en', 'es', 'fr', 'vi', 'ja', 'zh'] // Supported languages
});
// Use async wrapper for route handlers
app.post('/users', errorManager.asyncWrapper(async (req, res) => {
if (!req.body.email) {
throw new ValidationError('Email is required', [
{ field: 'email', message: 'Email field cannot be empty' }
]);
}
res.json({ success: true, data: { id: '123' } });
}));
// Add error handling middleware (must be last)
app.use(errorManager.expressMiddleware());Error Types
Built-in Error Classes
import {
ValidationError,
AuthenticationError,
AuthorizationError,
BusinessLogicError,
SystemError,
DatabaseError,
NetworkError,
ExternalServiceError
} from 'error-manager-pro';
// Validation error with field details
throw new ValidationError('Invalid input', [
{ field: 'email', message: 'Must be a valid email address' },
{ field: 'age', message: 'Must be at least 18' }
]);
// Authentication error
throw new AuthenticationError('Invalid credentials');
// Business logic error with custom message
throw new BusinessLogicError('Insufficient funds', 'INSUFFICIENT_FUNDS', {
title: 'Payment Failed',
description: 'Your account has insufficient funds for this transaction.',
action: 'Please add funds to your account or use a different payment method'
});Validation
Using Built-in Validators
import { Validator } from 'error-manager-pro';
import Joi from 'joi';
// Use common validation schemas
const email = Validator.validateEmail('[email protected]');
const password = Validator.validatePassword('SecurePass123!');
const uuid = Validator.validateUUID('123e4567-e89b-12d3-a456-426614174000');
// Create custom schemas
const userSchema = Joi.object({
email: Validator.commonSchemas.email,
password: Validator.commonSchemas.password,
age: Joi.number().integer().min(18).required()
});
// Validate data
try {
const userData = Validator.validate(userSchema, requestData);
// Process valid data
} catch (error) {
// Handle validation error with detailed field information
console.log(error.details); // Array of field-specific errors
}Multi-Language Support
Supported Languages
Error Manager Pro supports 13+ languages with professional translations:
- 🇺🇸 English (en) - Full support
- 🇪🇸 Spanish (es) - Full support
- 🇫🇷 French (fr) - Full support
- 🇻🇳 Vietnamese (vi) - Full support
- 🇯🇵 Japanese (ja) - Full support
- 🇨🇳 Chinese (zh) - Full support
- 🇩🇪 German (de) - Ready for expansion
- 🇮🇹 Italian (it) - Ready for expansion
- 🇵🇹 Portuguese (pt) - Ready for expansion
- 🇷🇺 Russian (ru) - Ready for expansion
- 🇰🇷 Korean (ko) - Ready for expansion
- 🇸🇦 Arabic (ar) - Ready for expansion
- 🇮🇳 Hindi (hi) - Ready for expansion
Basic Multi-Language Usage
import { I18nManager, ValidationError, BaseCustomError } from 'error-manager-pro';
// Initialize i18n manager
const i18nManager = new I18nManager({
defaultLanguage: 'en',
supportedLanguages: ['en', 'es', 'fr', 'vi', 'ja', 'zh'],
fallbackLanguage: 'en',
detectFromHeaders: true
});
// Set up error classes to use i18n
BaseCustomError.setI18nManager(i18nManager);
// Create errors in user's language
i18nManager.setLanguage('es'); // Switch to Spanish
throw new ValidationError(
i18nManager.translate('VALIDATION_ERROR'), // "Validación fallida"
[{ field: 'email', message: i18nManager.translate('INVALID_EMAIL') }]
);Language Detection
// Automatically detect language from HTTP headers
app.use((req, res, next) => {
const language = i18nManager.detectLanguageFromHeader(req.headers['accept-language']);
i18nManager.setLanguage(language);
next();
});
// Manual language switching
app.post('/set-language', (req, res) => {
const { language } = req.body;
if (i18nManager.isLanguageSupported(language)) {
i18nManager.setLanguage(language);
res.json({ success: true, currentLanguage: language });
}
});Custom Translations
// Add custom translations
i18nManager.addCustomTranslations('en', {
CUSTOM_ERROR: 'Custom error message in English'
});
i18nManager.addCustomTranslations('es', {
CUSTOM_ERROR: 'Mensaje de error personalizado en español'
});
// Use custom translations
const message = i18nManager.translate('CUSTOM_ERROR', 'es');Localized Formatting
// Format dates and numbers according to locale
const date = new Date();
const number = 1234567.89;
console.log('English:', i18nManager.formatDate(date, 'en')); // December 25, 2023
console.log('Spanish:', i18nManager.formatDate(date, 'es')); // 25 de diciembre de 2023
console.log('Japanese:', i18nManager.formatDate(date, 'ja')); // 2023年12月25日
console.log('English:', i18nManager.formatNumber(number, 'en')); // 1,234,567.89
console.log('Spanish:', i18nManager.formatNumber(number, 'es')); // 1.234.567,89
console.log('French:', i18nManager.formatNumber(number, 'fr')); // 1 234 567,89Configuration Options
interface ErrorManagerConfig {
logLevel?: string; // 'error', 'warn', 'info', 'debug'
includeStack?: boolean; // Include stack traces (default: true)
logToFile?: boolean; // Enable file logging
logFilePath?: string; // Path to log file
environment?: 'development' | 'production' | 'test';
enableConsoleColors?: boolean; // Colored console output
maxLogFileSize?: string; // Max log file size (e.g., '5m')
maxFiles?: number; // Number of log files to keep
// Multi-language configuration
language?: string; // Default language (e.g., 'en', 'es')
detectLanguageFromHeaders?: boolean; // Auto-detect from Accept-Language header
supportedLanguages?: string[]; // List of supported language codes
customTranslations?: Record<string, Record<string, string>>; // Custom translations
}Advanced Features
Performance Monitoring
app.get('/api/data', errorManager.asyncWrapper(async (req, res) => {
const startTime = Date.now();
// Your operation here
const data = await fetchData();
// Log performance metrics
const duration = Date.now() - startTime;
errorManager.logPerformance('fetchData', duration, {
requestId: req.headers['x-request-id']
});
res.json({ success: true, data });
}));Health Check Endpoint
app.get('/health', (req, res) => {
const healthStatus = errorManager.getHealthStatus();
res.status(healthStatus.status === 'healthy' ? 200 : 503).json({
success: healthStatus.status === 'healthy',
data: {
status: healthStatus.status,
errorRate: healthStatus.errorRate,
uptime: process.uptime()
}
});
});Custom Error Types
import { BaseCustomError, ErrorCategory, ErrorSeverity } from 'error-manager-pro';
class PaymentError extends BaseCustomError {
constructor(message: string, paymentMethod: string) {
super(
'PAYMENT_ERROR',
message,
ErrorCategory.BUSINESS_LOGIC,
ErrorSeverity.HIGH,
402,
{
title: 'Payment Failed',
description: `Payment failed using ${paymentMethod}. Please try again.`,
action: 'Try a different payment method or contact support'
}
);
}
}Error Response Format
All errors follow a consistent response format:
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"category": "validation",
"severity": "medium",
"userMessage": {
"title": "Invalid Input Data",
"description": "Please correct the following errors and try again.",
"action": "Review the highlighted fields below"
},
"details": [
{
"field": "email",
"message": "Please provide a valid email address",
"code": "string.email",
"value": "invalid-email"
}
],
"timestamp": "2023-12-07T10:30:00.000Z",
"requestId": "req_1701944200000_abc123"
}
}Best Practices
1. Use Specific Error Types
// Good
throw new ValidationError('Email is invalid', [
{ field: 'email', message: 'Must be a valid email format' }
]);
// Avoid
throw new Error('Invalid email');2. Provide User-Friendly Messages
throw new BusinessLogicError(
'Order cannot be processed',
'ORDER_LIMIT_EXCEEDED',
{
title: 'Order Limit Exceeded',
description: 'You have reached your daily order limit of 10 orders.',
action: 'Please try again tomorrow or contact support to increase your limit'
}
);3. Use Async Wrapper for Route Handlers
// Always wrap async route handlers
app.post('/api/users', errorManager.asyncWrapper(async (req, res) => {
// Your async code here
}));4. Configure for Environment
const config: ErrorManagerConfig = {
environment: process.env.NODE_ENV as 'development' | 'production',
includeStack: process.env.NODE_ENV === 'development',
logLevel: process.env.NODE_ENV === 'production' ? 'error' : 'debug',
logToFile: process.env.NODE_ENV === 'production'
};Examples
See the /examples directory for complete implementation examples including:
- Express.js API with error handling
- Validation examples
- Custom error types
- Performance monitoring
- Health checks
Contributing
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
License
MIT License - see LICENSE file for details.
Support
For issues and questions:
- GitHub Issues: Create an issue
- Email: [email protected]
Built with ❤️ for professional Node.js applications.
