### Node.js Development Commands Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Provides essential command-line instructions for developing and maintaining the NodeFling project, including dependency installation, building, testing, linting, and formatting. ```bash # Install dependencies npm install # Build the library npm run build # Run tests npm test # Run tests in watch mode npm run test:watch # Lint code npm run lint # Format code npm run format ``` -------------------------------- ### Install Nodefling Package Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Installs the nodefling library using various package managers (npm, pnpm, yarn). This is the initial step to integrate nodefling into your Node.js project. ```bash npm install nodefling ``` ```bash pnpm add nodefling ``` ```bash yarn add nodefling ``` -------------------------------- ### Throwing an Unauthorized Exception in TypeScript Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Illustrates throwing an UnauthorizedException for authentication failures. Examples cover cases with specific details like token expiration and missing credentials, including options for customizing the log level. ```typescript import { UnauthorizedException } from 'nodefling'; // Authentication failure throw new UnauthorizedException({ message: 'Invalid or expired token', details: { reason: 'Token expired', expiredAt: '2025-01-01T00:00:00Z' }, requestId: 'req-456' }); // Missing credentials throw new UnauthorizedException({ message: 'Authentication required', details: { authMethod: 'Bearer token' }, logLevel: 'warn' }); ``` -------------------------------- ### Throwing a Not Found Exception in TypeScript Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Provides an example of throwing a NotFoundException for missing resources or endpoints. It demonstrates specifying the message and details, such as the userId and search criteria, and includes the expected HTTP status code and error response format. ```typescript import { NotFoundException } from 'nodefling'; throw new NotFoundException({ message: 'User not found', details: { userId: '123', searchedBy: 'id' }, requestId: 'req-101' }); // Expected output: // Status: 404 // { // "error": { // "name": "NotFoundException", // "message": "User not found", // "code": "NOT_FOUND", // "statusCode": 404 // } // } ``` -------------------------------- ### Complete Express Integration with Nodefling Middleware Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt A comprehensive example demonstrating the integration of multiple Nodefling middleware components within an Express application. This includes request ID generation, logging, security headers, asynchronous error handling, input validation, and a global error handler. It showcases how to use custom exceptions like NotFoundException and ValidationException. ```typescript import express from 'express'; import { errorHandler, requestIdMiddleware, asyncErrorHandler, requestLoggerMiddleware, securityHeadersMiddleware, NotFoundException, ValidationException, validateRequiredFields, validateEmail } from 'nodefling'; const app = express(); // Middleware stack app.use(express.json()); app.use(requestIdMiddleware); app.use(requestLoggerMiddleware); app.use(securityHeadersMiddleware); // Routes with automatic error handling app.post('/users', asyncErrorHandler(async (req, res) => { // Validate required fields try { validateRequiredFields(req.body, ['name', 'email']); } catch (error) { throw new ValidationException({ message: error.message, details: { body: req.body } }); } // Validate email format if (!validateEmail(req.body.email)) { throw new ValidationException({ message: 'Invalid email format', details: { email: req.body.email } }); } const user = await createUser(req.body); res.status(201).json({ user, requestId: req.requestId }); })); app.get('/users/:id', asyncErrorHandler(async (req, res) => { const user = await findUser(req.params.id); if (!user) { throw new NotFoundException({ message: 'User not found', details: { userId: req.params.id } }); } res.json({ user, requestId: req.requestId }); })); // Global error handler (must be last) app.use(errorHandler); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` -------------------------------- ### Input Validation with NodeFling Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Shows how to validate required fields and specific formats like email and URLs using NodeFling's validation functions. Includes an example of throwing a ValidationException for invalid data. ```typescript import { validateRequiredFields, validateEmail, validateUrl } from 'nodefling'; // Validate required fields validateRequiredFields(data, ['name', 'email', 'age']); // Validate formats if (!validateEmail(email)) { throw new ValidationException({ message: 'Invalid email format', details: { email }, }); } ``` -------------------------------- ### Throwing a Conflict Exception in TypeScript Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates the use of ConflictException when a resource operation conflicts with the current state of the resource. The example shows how to include details like the conflicting email and the ID of the existing user. ```typescript import { ConflictException } from 'nodefling'; throw new ConflictException({ message: 'Email already registered', details: { email: 'user@example.com', existingUserId: 'user-456' }, requestId: 'req-202' }); ``` -------------------------------- ### Throwing a Bad Request Exception in TypeScript Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates how to throw a BadRequestException for malformed client requests. Includes basic usage and an example with full options, specifying message, details, requestId, and context. The expected API response format is also shown. ```typescript import { BadRequestException } from 'nodefling'; // Basic usage throw new BadRequestException({ message: 'Invalid email format', details: { email: 'invalid-email' } }); // With full options throw new BadRequestException({ message: 'Missing required parameters', details: { missing: ['username', 'password'], provided: ['email'] }, requestId: 'req-123', context: { endpoint: '/api/login', method: 'POST' } }); // API Response: // { // "error": { // "name": "BadRequestException", // "message": "Invalid email format", // "code": "BAD_REQUEST", // "statusCode": 400, // "requestId": "req-123" // } // } ``` -------------------------------- ### GET /users/:id Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Retrieves a user by their ID. Returns the user object or throws a NotFoundException if the user is not found. ```APIDOC ## GET /users/:id ### Description Retrieves a user by their ID. Returns the user object or throws a NotFoundException if the user is not found. ### Method GET ### Endpoint `/users/:id` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to retrieve. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **user** (object) - The user object. - **requestId** (string) - The unique identifier for the request. #### Response Example ```json { "user": { "id": "some-uuid", "name": "John Doe", "email": "john.doe@example.com" }, "requestId": "1735689600000-abc123def" } ``` ``` -------------------------------- ### Throwing an Internal Server Error Exception in TypeScript Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates throwing an InternalServerErrorException for unexpected server-side issues. The example includes details about the error, such as database connection pool status, the original error object, and specifies the log level. ```typescript import { InternalServerErrorException } from 'nodefling'; throw new InternalServerErrorException({ message: 'Database connection pool exhausted', details: { poolSize: 10, activeConnections: 10 }, cause: originalError, logLevel: 'error' }); ``` -------------------------------- ### Throwing a Forbidden Exception in TypeScript Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Shows how to raise a ForbiddenException when an authenticated user lacks the necessary permissions. The example includes details about the user's role, the required role, and the resource accessed, along with userId and requestId. ```typescript import { ForbiddenException } from 'nodefling'; throw new ForbiddenException({ message: 'Access denied to admin resources', details: { userRole: 'user', requiredRole: 'admin', resource: '/admin/users' }, userId: 'user-789', requestId: 'req-789' }); ``` -------------------------------- ### Express.js Error Handling Middleware (NodeFling) Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Shows how to integrate NodeFling's error handling capabilities into an Express.js application using middleware. It includes setup for request ID generation and asynchronous error handling. ```typescript import express from 'express'; import { errorHandler, requestIdMiddleware, asyncErrorHandler, } from 'nodefling'; const app = express(); app.use(requestIdMiddleware); app.use(asyncErrorHandler); app.use(errorHandler); ``` -------------------------------- ### Error Handling with Retry Logic (NodeFling) Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Provides an example of handling errors from external services and integrating them with NodeFling's retry mechanism. It defines a fetch function that throws ExternalServiceException and then uses retryWithBackoff to handle potential failures. ```typescript import { ExternalServiceException, retryWithBackoff } from 'nodefling'; const fetchUserData = async (userId: string) => { try { const response = await fetch(`/api/users/${userId}`); if (!response.ok) { throw new ExternalServiceException( 'UserService', `/api/users/${userId}`, { retryable: true, details: { statusCode: response.status }, } ); } return response.json(); } catch (error) { throw new ExternalServiceException('UserService', `/api/users/${userId}`, { retryable: true, cause: error, }); } }; // Use with retry logic const userData = await retryWithBackoff(() => fetchUserData('123')); ``` -------------------------------- ### Throwing an Unprocessable Entity Exception in TypeScript Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Illustrates throwing an UnprocessableEntityException for requests that are semantically incorrect. The example includes a message and details explaining the business logic violation, such as an inability to delete a user with active orders. ```typescript import { UnprocessableEntityException } from 'nodefling'; throw new UnprocessableEntityException({ message: 'Invalid business logic', details: { reason: 'Cannot delete user with active orders', activeOrders: 5 } }); ``` -------------------------------- ### Throw CacheException in TypeScript Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Illustrates throwing a CacheException for errors during cache operations like setting or getting data. It includes the operation performed, the key involved, and details about the cache type and error encountered. This exception is often retryable and defaults to an HTTP status of 500. ```typescript import { CacheException } from 'nodefling'; // Constructor signature: (operation, key, options) throw new CacheException('SET', 'user:session:123', { details: { cacheType: 'Redis', error: 'Connection timeout' }, retryable: true, isOperational: false }); // Automatically generates message: "Cache operation failed: SET" // Status: 500 ``` -------------------------------- ### Run Development Commands for nodefling Source: https://github.com/fullstack-dopamine/nodefling/blob/main/CONTRIBUTING.md This section lists common npm scripts for developing the nodefling project. These commands help with dependency management, testing, code quality, and building the project. ```sh npm install npm test npm run lint npm run format npm run typecheck npm run build ``` -------------------------------- ### Handle Configuration Errors (TypeScript) Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates throwing a ConfigurationException for issues with application configuration settings, such as missing environment variables. This often indicates a 500 status and is not usually operational. ```typescript import { ConfigurationException } from 'nodefling'; // Constructor signature: (configKey, options) throw new ConfigurationException('DATABASE_URL', { details: { reason: 'Environment variable not set', requiredFormat: 'postgresql://user:pass@host:port/db' }, isOperational: false }); // Automatically generates message: "Configuration error: DATABASE_URL" // Status: 500 ``` -------------------------------- ### Handle Resource Not Found Errors (TypeScript) Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates throwing a ResourceNotFoundException for a missing resource. The constructor automatically formats a descriptive message and indicates a 404 status. ```typescript import { ResourceNotFoundException } from 'nodefling'; // Constructor signature: (resourceType, resourceId, options) throw new ResourceNotFoundException('Product', 'prod-789', { requestId: 'req-303', context: { searchedIn: 'database', table: 'products' } }); // Automatically generates message: "Product with id 'prod-789' not found" // Status: 404 ``` -------------------------------- ### Nodefling BaseException Instance Methods Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates various instance methods available on exceptions created with nodefling, such as `toJSON`, `toResponse`, `isClientError`, `isServerError`, `isRetryable`, `addContext`, `addDetail`, `setUserId`, and `getStatusMessage`. These methods help in converting errors to different formats, checking error types, adding context, and retrieving status messages. ```typescript import { NotFoundException } from 'nodefling'; const error = new NotFoundException({ message: 'User not found', details: { userId: '123' }, requestId: 'req-789' }); // Convert to JSON const json = error.toJSON(); console.log(json); // { // name: "NotFoundException", // message: "User not found", // statusCode: 404, // code: "NOT_FOUND", // details: { userId: "123" }, // timestamp: "2025-01-01T12:00:00.000Z", // requestId: "req-789", // ... // } // Get API response format const response = error.toResponse(); console.log(response); // { // error: { // name: "NotFoundException", // message: "User not found", // code: "NOT_FOUND", // statusCode: 404, // requestId: "req-789" // } // } // Check error type console.log(error.isClientError()); // true (4xx) console.log(error.isServerError()); // false (5xx) console.log(error.isRetryable()); // false // Add context and details error .addContext('ip', '192.168.1.1') .addContext('userAgent', 'Mozilla/5.0') .addDetail('searchedBy', 'email') .setUserId('user-456'); // Get status message console.log(error.getStatusMessage()); // "Not Found" ``` -------------------------------- ### Create Git Branch for Features or Fixes Source: https://github.com/fullstack-dopamine/nodefling/blob/main/CONTRIBUTING.md This command shows how to create a new git branch for either a new feature or a bug fix. It uses standard git commands to checkout a new branch with a descriptive name following common conventions. ```sh git checkout -b feat/your-feature-name # or git checkout -b fix/your-bug-description ``` -------------------------------- ### Handle Authentication Failures (TypeScript) Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Shows how to throw an AuthenticationException when the authentication process fails, specifying the reason and remaining attempts. ```typescript import { AuthenticationException } from 'nodefling'; throw new AuthenticationException({ message: 'Authentication failed', details: { reason: 'Invalid password', attemptsRemaining: 2 }, userId: 'user-123' }); ``` -------------------------------- ### POST /users Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Creates a new user after validating required fields and email format. Returns the created user and the request ID. ```APIDOC ## POST /users ### Description Creates a new user after validating required fields and email format. Returns the created user and the request ID. ### Method POST ### Endpoint `/users` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) - **user** (object) - The created user object. - **requestId** (string) - The unique identifier for the request. #### Response Example ```json { "user": { "id": "some-uuid", "name": "John Doe", "email": "john.doe@example.com" }, "requestId": "1735689600000-abc123def" } ``` ``` -------------------------------- ### Format and Control Error Logging with Nodefling Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates how to format errors for logging and control whether an error should be logged based on its log level. It uses `formatErrorForLogging` and `shouldLogError` from the nodefling library. Dependencies include the nodefling library. ```typescript import { formatErrorForLogging, shouldLogError, NotFoundException, InternalServerErrorException } from 'nodefling'; // Format error for logging const error = new NotFoundException({ message: 'User not found', details: { userId: '123' } }); const logMessage = formatErrorForLogging(error, { userId: 'user-456', action: 'fetch_profile', endpoint: '/api/users/123' }); console.log(logMessage); // "NotFoundException: User not found | Status: 404 | Timestamp: 2025-01-01T12:00:00.000Z | Context: {...}" // Control logging based on log level const infoError = new NotFoundException({ message: 'Resource not found', logLevel: 'info' }); const criticalError = new InternalServerErrorException({ message: 'Database connection failed', logLevel: 'error' }); // Check if error should be logged at 'error' level if (shouldLogError(infoError, 'error')) { console.error(formatErrorForLogging(infoError)); } // false - won't log (info < error) if (shouldLogError(criticalError, 'error')) { console.error(formatErrorForLogging(criticalError)); } // true - will log ``` -------------------------------- ### HTTP Status Codes and Helpers Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Provides constants for HTTP status codes and utility functions to categorize them, simplifying status code management in applications. ```APIDOC ## HTTP Status Codes ### StatusCodes Constants Comprehensive HTTP status code constants for all response types. #### Usage ```typescript import { StatusCodes, StatusMessages } from 'nodefling'; // Success codes console.log(StatusCodes.OK); // 200 console.log(StatusCodes.CREATED); // 201 console.log(StatusCodes.NO_CONTENT); // 204 // Client error codes console.log(StatusCodes.BAD_REQUEST); // 400 console.log(StatusCodes.UNAUTHORIZED); // 401 console.log(StatusCodes.FORBIDDEN); // 403 console.log(StatusCodes.NOT_FOUND); // 404 console.log(StatusCodes.CONFLICT); // 409 console.log(StatusCodes.UNPROCESSABLE_ENTITY); // 422 console.log(StatusCodes.TOO_MANY_REQUESTS); // 429 // Server error codes console.log(StatusCodes.INTERNAL_SERVER_ERROR); // 500 console.log(StatusCodes.SERVICE_UNAVAILABLE); // 503 console.log(StatusCodes.GATEWAY_TIMEOUT); // 504 // Get status messages console.log(StatusMessages[StatusCodes.OK]); // "OK" console.log(StatusMessages[StatusCodes.NOT_FOUND]); // "Not Found" console.log(StatusMessages[StatusCodes.CONFLICT]); // "Conflict" ``` ### Status Code Category Helpers Utility functions to categorize HTTP status codes. #### Functions - `isStatusCodeCategory(statusCode: number, category: string): boolean` - Checks if a status code belongs to a specific category ('SUCCESS', 'CLIENT_ERROR', 'SERVER_ERROR'). - `getStatusCodeCategory(statusCode: number): string` - Returns the category of a given status code. #### Usage ```typescript import { StatusCodeCategories, isStatusCodeCategory, getStatusCodeCategory } from 'nodefling'; // Check if status code belongs to category const is4xx = isStatusCodeCategory(404, 'CLIENT_ERROR'); // true const is5xx = isStatusCodeCategory(404, 'SERVER_ERROR'); // false // Get category of status code const category = getStatusCodeCategory(201); // "SUCCESS" const errorCategory = getStatusCodeCategory(500); // "SERVER_ERROR" // Access category arrays console.log(StatusCodeCategories.SUCCESS); // [200, 201, 202, ...] console.log(StatusCodeCategories.CLIENT_ERROR); // [400, 401, 403, ...] console.log(StatusCodeCategories.SERVER_ERROR); // [500, 501, 502, ...] ``` ``` -------------------------------- ### Error Handling with NodeFling Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Demonstrates how to check error types, create standardized error responses, and implement retry logic using NodeFling's utilities. It leverages functions like isBaseException, createErrorResponse, and retryWithBackoff. ```typescript import { isBaseException, isRetryableError, createErrorResponse, retryWithBackoff, } from 'nodefling'; // Check error types if (isBaseException(error)) { console.log(error.statusCode); console.log(error.isRetryable()); } // Create standardized error response const response = createErrorResponse(error, includeStack); // Retry with exponential backoff const result = await retryWithBackoff( () => fetchData(), (maxRetries = 3), (baseDelay = 1000) ); ``` -------------------------------- ### Nodefling HTTP Status Codes and Messages Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Demonstrates how to access predefined HTTP status codes and their corresponding messages using `StatusCodes` and `StatusMessages` from nodefling. This ensures consistent use of HTTP status codes. ```typescript import { StatusCodes, StatusMessages } from 'nodefling'; // Use predefined status codes console.log(StatusCodes.OK); // 200 console.log(StatusCodes.BAD_REQUEST); // 400 console.log(StatusCodes.INTERNAL_SERVER_ERROR); // 500 // Get status messages console.log(StatusMessages[StatusCodes.OK]); // "OK" console.log(StatusMessages[StatusCodes.NOT_FOUND]); // "Not Found" ``` -------------------------------- ### Handle Insufficient Permissions Errors (TypeScript) Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Shows how to throw an InsufficientPermissionsException when a user lacks the necessary permissions for an action, resulting in a 403 status. ```typescript import { InsufficientPermissionsException } from 'nodefling'; // Constructor signature: (requiredPermission, options) throw new InsufficientPermissionsException('admin:write', { userId: 'user-555', details: { userPermissions: ['user:read', 'user:write'], requiredPermission: 'admin:write' } }); // Automatically generates message: "Insufficient permissions. Required: admin:write" // Status: 403 ``` -------------------------------- ### Basic Nodefling Exception Usage Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Demonstrates the basic usage of nodefling's exception classes like BadRequestException and NotFoundException. These exceptions can be thrown with custom messages and details, improving error reporting. ```typescript import { BadRequestException, NotFoundException, StatusCodes, errorHandler, } from 'nodefling'; // Basic usage throw new BadRequestException({ message: 'Invalid email format', details: { email: 'invalid-email' }, }); // With custom options throw new NotFoundException({ message: 'User not found', details: { userId: '123' }, requestId: 'req-123', retryable: false, }); ``` -------------------------------- ### Custom Exception Creation in NodeFling Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Illustrates how to create custom business exceptions that extend NodeFling's BaseException. This allows for detailed error information including business rules, status codes, and retryability. ```typescript import { BaseException } from 'nodefling'; class CustomBusinessException extends BaseException { constructor(businessRule: string, options = {}) { super({ message: `Business rule violated: ${businessRule}`, statusCode: 422, code: 'BUSINESS_RULE_VIOLATION', details: { businessRule }, retryable: false, logLevel: 'warn', ...options, }); } } throw new CustomBusinessException('minimum_order_amount', { requestId: 'req-123', context: { orderAmount: 50, minimumAmount: 100 }, }); ``` -------------------------------- ### Request Tracking Utilities (NodeFling) Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Demonstrates the use of NodeFling utilities for generating unique request IDs and formatting errors for logging purposes, enhancing traceability within applications. ```typescript import { generateRequestId, formatErrorForLogging } from 'nodefling'; // Generate unique request ID const requestId = generateRequestId(); // "1703123456789-abc123def" // Format error for logging const logMessage = formatErrorForLogging(error, { userId: 'user-123', action: 'create_order', }); ``` -------------------------------- ### Koa Error Handling Middleware (NodeFling) Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Demonstrates the implementation of NodeFling's errorHandler as a Koa middleware, providing a centralized way to manage errors within a Koa application. ```typescript import Koa from 'koa'; import { errorHandler } from 'nodefling'; const app = new Koa(); app.use(async (ctx, next) => { try { await next(); } catch (error) { const { statusCode, response } = errorHandler( error, ctx.request, ctx.response ); ctx.status = statusCode; ctx.body = response; } }); ``` -------------------------------- ### Handle Service Unavailable with Retry (TypeScript) Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates throwing a ServiceUnavailableException for temporary service outages. This exception is marked as retryable and includes estimated downtime details. ```typescript import { ServiceUnavailableException } from 'nodefling'; throw new ServiceUnavailableException({ message: 'Service temporarily unavailable', details: { estimatedDowntime: '5 minutes' }, retryable: true }); ``` -------------------------------- ### Fastify Error Handling Integration (NodeFling) Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Illustrates how to configure NodeFling's errorHandler within a Fastify application by setting a custom error handler that utilizes the NodeFling utility. ```typescript import fastify from 'fastify'; import { errorHandler } from 'nodefling'; const app = fastify(); app.setErrorHandler((error, request, reply) => { const { statusCode, response } = errorHandler(error, request, reply); reply.status(statusCode).send(response); }); ``` -------------------------------- ### Handle Duplicate Resource Errors (TypeScript) Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Illustrates throwing a DuplicateResourceException when attempting to create a resource that already exists based on a unique field. This typically results in a 409 status. ```typescript import { DuplicateResourceException } from 'nodefling'; // Constructor signature: (resourceType, field, value, options) throw new DuplicateResourceException('User', 'email', 'john@example.com', { requestId: 'req-404', details: { existingUserId: 'user-999' } }); // Automatically generates message: "User with email 'john@example.com' already exists" // Status: 409 ``` -------------------------------- ### Request Logger Middleware Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Logs incoming requests with timing and status information. It logs 2xx/3xx responses to console.log and 4xx/5xx responses to console.error. ```APIDOC ## Request Logger Middleware ### Description Logs all incoming requests with timing and status information. ### Method Middleware ### Endpoint N/A (Applied globally via `app.use()`) ### Parameters None ### Request Body None ### Request Example ```typescript import express from 'express'; import { requestLoggerMiddleware } from 'nodefling'; const app = express(); app.use(requestLoggerMiddleware); // Example log output: // GET /api/users 200 45ms - 1735689600000-abc123def // POST /api/users 400 12ms - 1735689600001-xyz789ghi ``` ### Response None (logs to console) ### Response Example None ``` -------------------------------- ### NetworkException for Network Operation Failures (TypeScript) Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates how to throw and handle NetworkException for network operation failures. This exception includes retry support and allows for custom details about the failure. It's useful for abstracting network-related errors in applications. ```typescript import { NetworkException } from 'nodefling'; // Constructor signature: (operation, url, options) throw new NetworkException('FETCH', 'https://api.example.com/data', { details: { errorCode: 'ECONNREFUSED', timeout: 3000 }, retryable: true, isOperational: false }); // Automatically generates message: "Network operation failed: FETCH" // Status: 503 ``` -------------------------------- ### Handle Rate Limit Exceeded Errors (TypeScript) Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates throwing a RateLimitExceededException when an API rate limit is breached. It includes retry configuration and details about the limit and reset time, typically a 429 status. ```typescript import { RateLimitExceededException } from 'nodefling'; // Constructor signature: (limit, window, options) throw new RateLimitExceededException(100, '1 minute', { requestId: 'req-505', details: { currentRequests: 105, resetAt: new Date(Date.now() + 60000).toISOString() }, retryable: true }); // Automatically generates message: "Rate limit exceeded. Limit: 100 requests per 1 minute" // Status: 429 ``` -------------------------------- ### NetworkException Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Handles network operation failures with built-in retry support. It automatically generates informative messages and sets appropriate HTTP status codes. ```APIDOC ## NetworkException ### Description Exception for network operation failures with retry support. ### Constructor `NetworkException(operation: string, url: string, options?: object)` ### Parameters - **operation** (string) - Required - The name of the network operation that failed. - **url** (string) - Required - The URL that was being accessed. - **options** (object) - Optional - Additional options for the exception. - **details** (object) - Optional - Specific details about the error (e.g., `errorCode`, `timeout`). - **retryable** (boolean) - Optional - Indicates if the operation can be retried. - **isOperational** (boolean) - Optional - Indicates if the error is operational. ### Example Usage ```typescript import { NetworkException } from 'nodefling'; throw new NetworkException('FETCH', 'https://api.example.com/data', { details: { errorCode: 'ECONNREFUSED', timeout: 3000 }, retryable: true, isOperational: false }); ``` ### Response - **message** (string) - Automatically generated message (e.g., "Network operation failed: FETCH"). - **status** (number) - The HTTP status code, defaults to 503 (Service Unavailable). ``` -------------------------------- ### HTTP Status Code Constants and Helpers (TypeScript) Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Provides constants for all HTTP status codes and utility functions to categorize them. This facilitates standardized handling of HTTP responses and errors by mapping codes to their meanings and categories (Success, Client Error, Server Error). ```typescript import { StatusCodes, StatusMessages, StatusCodeCategories, isStatusCodeCategory, getStatusCodeCategory } from 'nodefling'; // Success codes console.log(StatusCodes.OK); // 200 console.log(StatusCodes.CREATED); // 201 console.log(StatusCodes.NO_CONTENT); // 204 // Client error codes console.log(StatusCodes.BAD_REQUEST); // 400 console.log(StatusCodes.UNAUTHORIZED); // 401 console.log(StatusCodes.FORBIDDEN); // 403 console.log(StatusCodes.NOT_FOUND); // 404 console.log(StatusCodes.CONFLICT); // 409 console.log(StatusCodes.UNPROCESSABLE_ENTITY); // 422 console.log(StatusCodes.TOO_MANY_REQUESTS); // 429 // Server error codes console.log(StatusCodes.INTERNAL_SERVER_ERROR); // 500 console.log(StatusCodes.SERVICE_UNAVAILABLE); // 503 console.log(StatusCodes.GATEWAY_TIMEOUT); // 504 // Get status messages console.log(StatusMessages[StatusCodes.OK]); // "OK" console.log(StatusMessages[StatusCodes.NOT_FOUND]); // "Not Found" console.log(StatusMessages[StatusCodes.CONFLICT]); // "Conflict" // Check if status code belongs to category const is4xx = isStatusCodeCategory(404, 'CLIENT_ERROR'); // true const is5xx = isStatusCodeCategory(404, 'SERVER_ERROR'); // false // Get category of status code const category = getStatusCodeCategory(201); // "SUCCESS" const errorCategory = getStatusCodeCategory(500); // "SERVER_ERROR" // Access category arrays console.log(StatusCodeCategories.SUCCESS); // [200, 201, 202, ...] console.log(StatusCodeCategories.CLIENT_ERROR); // [400, 401, 403, ...] console.log(StatusCodeCategories.SERVER_ERROR); // [500, 501, 502, ...] ``` -------------------------------- ### Security Headers Middleware for Express.js Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt This middleware automatically adds essential security headers to all HTTP responses. It helps protect your application against common web vulnerabilities like cross-site scripting (XSS) and clickjacking. It's configured using 'nodefling's securityHeadersMiddleware. ```typescript import express from 'express'; import { securityHeadersMiddleware } from 'nodefling'; const app = express(); // Add security headers to all responses app.use(securityHeadersMiddleware); // Automatically adds: // - X-Content-Type-Options: nosniff // - X-Frame-Options: DENY // - X-XSS-Protection: 1; mode=block // - Strict-Transport-Security: max-age=31536000; includeSubDomains // Your routes... app.get('/', (req, res) => { res.send('Secure response with headers'); }); ``` -------------------------------- ### Security Headers Middleware Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Adds essential security headers to all outgoing responses, enhancing the security posture of your Express application. ```APIDOC ## Security Headers Middleware ### Description Adds security headers to all responses. ### Method Middleware ### Endpoint N/A (Applied globally via `app.use()`) ### Parameters None ### Request Body None ### Request Example ```typescript import express from 'express'; import { securityHeadersMiddleware } from 'nodefling'; const app = express(); app.use(securityHeadersMiddleware); // Automatically adds: // - X-Content-Type-Options: nosniff // - X-Frame-Options: DENY // - X-XSS-Protection: 1; mode=block // - Strict-Transport-Security: max-age=31536000; includeSubDomains ``` ### Response Adds headers to the response. ### Response Example None ``` -------------------------------- ### Global Error Handler Middleware Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt A centralized middleware for handling all errors within an Express application, providing standardized error responses and logging. ```APIDOC ## Express Middleware: Global Error Handler ### Description Central error handling middleware for standardized error responses and logging across the application. ### Method `app.use(errorHandler)` ### Placement This middleware must be registered as the *last* middleware in the Express application. ### Usage ```typescript import express from 'express'; import { errorHandler, requestIdMiddleware, BadRequestException } from 'nodefling'; const app = express(); // Add request ID tracking app.use(requestIdMiddleware); // Your routes app.post('/api/users', (req, res) => { if (!req.body.email) { throw new BadRequestException({ message: 'Email is required', details: { field: 'email' } }); } res.json({ success: true }); }); // Global error handler (must be last middleware) app.use(errorHandler); ``` ### Features - Automatically catches errors thrown by routes or other middleware. - Logs errors with relevant context (including request ID). - Formats error responses consistently. - Sets appropriate HTTP status codes based on the exception type. - Includes stack traces in development environments for easier debugging. ``` -------------------------------- ### Async Error Handler Middleware Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Wraps asynchronous route handlers to automatically catch errors and pass them to the Express error handling mechanism. ```APIDOC ## Express Middleware: Async Error Handler ### Description Wraps async route handlers to automatically catch and forward errors to the global error handler. ### Method `asyncErrorHandler(handler: Function): Function` ### Usage ```typescript import express from 'express'; import { asyncErrorHandler, NotFoundException } from 'nodefling'; const app = express(); // Wrap async routes with asyncErrorHandler app.get('/users/:id', asyncErrorHandler(async (req, res) => { const user = await getUserFromDatabase(req.params.id); if (!user) { throw new NotFoundException({ message: 'User not found', details: { userId: req.params.id } }); } res.json(user); })); ``` ### Benefits - Eliminates the need for `try-catch` blocks within asynchronous route handlers. - Ensures all errors from async operations are consistently handled. ``` -------------------------------- ### Throw FileSystemException in TypeScript Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Shows how to throw a FileSystemException for errors occurring during file system operations like reading or writing files. It captures the operation, the file path, and specific error details such as error codes. This exception is typically marked as not operational and results in an HTTP status of 500. ```typescript import { FileSystemException } from 'nodefling'; // Constructor signature: (operation, path, options) throw new FileSystemException('READ', '/uploads/avatar.jpg', { details: { errorCode: 'ENOENT', errorMessage: 'File not found' }, cause: fsError, isOperational: false }); // Automatically generates message: "File system operation failed: READ" // Status: 500 ``` -------------------------------- ### Nodefling HTTP Exception Types Source: https://github.com/fullstack-dopamine/nodefling/blob/main/README.md Imports various HTTP-related exception classes provided by nodefling, covering common HTTP status codes from 400 to 504. These classes help standardize HTTP error responses. ```typescript import { BadRequestException, // 400 UnauthorizedException, // 401 ForbiddenException, // 403 NotFoundException, // 404 MethodNotAllowedException, // 405 ConflictException, // 409 UnprocessableEntityException, // 422 TooManyRequestsException, // 429 InternalServerErrorException, // 500 ServiceUnavailableException, // 503 GatewayTimeoutException, // 504 } from 'nodefling'; ``` -------------------------------- ### Error Utility Functions Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Provides functions to check error types (BaseException, retryable, operational) and to create standardized error responses. ```APIDOC ## Error Utility Functions ### Description Functions to check error types and create standardized error responses. ### Methods - **isBaseException(error): boolean** - **isRetryableError(error): boolean** - **isOperationalError(error): boolean** - **createErrorResponse(error, includeStackTrace: boolean): object** ### Parameters #### `isBaseException` - **error** (any) - The error object to check. #### `isRetryableError` - **error** (any) - The error object to check. #### `isOperationalError` - **error** (any) - The error object to check. #### `createErrorResponse` - **error** (any) - The error object to create a response from. - **includeStackTrace** (boolean) - Whether to include the stack trace in the response. ### Request Example (Checking Error Types) ```typescript import { isBaseException, isRetryableError, isOperationalError } from 'nodefling'; try { // ... some operation that might throw an error } catch (error) { if (isBaseException(error)) { console.log(error.statusCode); console.log(error.code); console.log(error.isRetryable()); console.log(error.details); } if (isRetryableError(error)) { console.log('Operation is retryable'); } if (isOperationalError(error)) { console.log('This is an expected operational error'); } else { console.log('This is an unexpected programming error'); } } ``` ### Request Example (Creating Error Response) ```typescript import { createErrorResponse, NotFoundException } from 'nodefling'; try { // ... operation that throws NotFoundException } catch (error) { const errorResponseDev = createErrorResponse(error, true); const errorResponseProd = createErrorResponse(error, false); // Use errorResponseDev or errorResponseProd based on environment } ``` ### Response Example (Development Mode) ```json { "error": { "name": "NotFoundException", "message": "User not found", "code": "NOT_FOUND", "statusCode": 404, "stack": "Error: User not found\n at ..." } } ``` ### Response Example (Production Mode) ```json { "error": { "name": "NotFoundException", "message": "User not found", "code": "NOT_FOUND", "statusCode": 404 } } ``` ``` -------------------------------- ### Handle Data Integrity Violations (TypeScript) Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Shows how to throw a DataIntegrityException for violations of database constraints, such as foreign key issues. This usually results in a 409 status. ```typescript import { DataIntegrityException } from 'nodefling'; // Constructor signature: (constraint, options) throw new DataIntegrityException('foreign_key_constraint', { details: { table: 'orders', column: 'user_id', referencedTable: 'users' } }); // Automatically generates message: "Data integrity constraint violated: foreign_key_constraint" // Status: 409 ``` -------------------------------- ### Request Logger Middleware for Express.js Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt This middleware logs details of incoming HTTP requests, including method, URL, status code, and response time. It leverages 'nodefling's requestIdMiddleware and requestLoggerMiddleware. Logs to console.log for success (2xx/3xx) and console.error for client errors (4xx/5xx). ```typescript import express from 'express'; import { requestIdMiddleware, requestLoggerMiddleware } from 'nodefling'; const app = express(); app.use(requestIdMiddleware); app.use(requestLoggerMiddleware); // Automatically logs: // "GET /api/users 200 45ms - 1735689600000-abc123def" // "POST /api/users 400 12ms - 1735689600001-xyz789ghi" // Routes... app.get('/api/users', (req, res) => { res.json({ users: [] }); }); // Logs to console.log for 2xx/3xx responses // Logs to console.error for 4xx/5xx responses ``` -------------------------------- ### Error Type Checking with Nodefling Utilities Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Demonstrates how to check the type and characteristics of caught errors using utility functions provided by Nodefling. It includes checks for whether an error is a BaseException instance, if it's safe to retry, or if it's an operational error versus a programming error. ```typescript import { isBaseException, isRetryableError, isOperationalError } from 'nodefling'; try { await someOperation(); } catch (error) { // Check if it's a Nodefling exception if (isBaseException(error)) { console.log(error.statusCode); // 404 console.log(error.code); // "NOT_FOUND" console.log(error.isRetryable()); // false console.log(error.details); // { userId: '123' } } // Check if error should be retried if (isRetryableError(error)) { // Retry logic here console.log('Will retry operation'); } // Check if error is operational (expected) vs programming error if (isOperationalError(error)) { console.log('Expected error, handle gracefully'); } else { console.log('Unexpected programming error, alert developers'); } } ``` -------------------------------- ### Creating Standardized Error Responses with Nodefling Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt This snippet shows how to generate consistent error response objects for API endpoints using the `createErrorResponse` function from Nodefling. It allows for conditional inclusion of the error stack trace, distinguishing between development and production environments. ```typescript import { createErrorResponse, NotFoundException } from 'nodefling'; try { const user = await findUser('123'); } catch (error) { // Create standardized error response const errorResponse = createErrorResponse(error, true); // Development mode (with stack trace): // { // "error": { // "name": "NotFoundException", // "message": "User not found", // "code": "NOT_FOUND", // "statusCode": 404, // "stack": "Error: User not found\n at ..." // } // } // Production mode (without stack trace): const prodResponse = createErrorResponse(error, false); // { // "error": { // "name": "NotFoundException", // "message": "User not found", // "code": "NOT_FOUND", // "statusCode": 404 // } // } return errorResponse; } ``` -------------------------------- ### Request ID Middleware Source: https://context7.com/fullstack-dopamine/nodefling/llms.txt Automatically generates and tracks unique request identifiers for each incoming request, improving log correlation and debugging. ```APIDOC ## Express Middleware: Request ID ### Description Automatically generates and tracks unique request identifiers for incoming requests. ### Method `app.use(requestIdMiddleware)` ### Endpoint Applies to all requests when used as middleware. ### Usage ```typescript import express from 'express'; import { requestIdMiddleware } from 'nodefling'; const app = express(); // Add request ID to all requests app.use(requestIdMiddleware); // Access request ID in routes app.get('/api/data', (req, res) => { console.log(req.requestId); // e.g., "1735689600000-abc123def" res.json({ data: 'example', requestId: req.requestId }); }); ``` ### Features - Generates a unique request ID. - Adds the request ID to the `req.requestId` property. - Includes the request ID in response headers as `X-Request-ID`. - Can accept an existing request ID from the `x-request-id` header. ```