qapinterface
Version:
Comprehensive API utilities for Node.js applications including authentication, security, request processing, and response handling with zero external dependencies
97 lines (91 loc) • 3.82 kB
JavaScript
/**
* HTTP Utilities and Error Handling Middleware
*
* SINGLE RESPONSIBILITY: Centralized HTTP error handling and response utilities ONLY
*
* DESIGN PHILOSOPHY:
* This module serves as the primary HTTP utilities hub, combining error handling middleware
* with response validation functions. The centralization reduces import complexity while
* maintaining clear separation of concerns within each utility.
*
* ERROR HANDLING STRATEGY:
* The middleware implements a defense-in-depth approach:
* 1. Comprehensive error logging with request context
* 2. Headers-sent protection to prevent double responses
* 3. Sanitized error responses that don't leak internal details
* 4. Consistent error format across all API endpoints
*
* WHY THIS APPROACH:
* - Centralized error handling prevents inconsistent error responses
* - Request context logging aids in debugging production issues
* - Headers-sent protection prevents application crashes from double responses
* - Standardized error format improves client-side error handling
*/
/**
* Express error handling middleware with comprehensive logging and safe responses.
*
* MIDDLEWARE DESIGN:
* Follows Express 4+ error handling conventions (4 parameters) and implements
* production-ready error handling patterns:
* - Detailed logging for debugging
* - Sanitized responses for security
* - Headers-sent protection for stability
*
* SECURITY CONSIDERATIONS:
* - Error messages are sanitized to prevent information disclosure
* - Stack traces are logged but never sent to clients
* - Request details are logged for audit trails
*
* @param {Error} err - The error object containing error details and stack trace
* @param {object} req - Express request object with HTTP context
* @param {object} res - Express response object for sending responses
* @param {function} next - Express next function for error propagation
*/
function errorHandlerMiddleware(err, req, res, next) {
// Comprehensive error logging: Include all relevant context for debugging
// Log to console as fallback since logger might be the source of the error
console.error('An unexpected error occurred:', {
// Error details: Message and stack trace for debugging
error: err.message,
stack: err.stack,
// Request context: Essential for reproducing and debugging issues
req: {
id: req.id, // Request correlation ID
method: req.method, // HTTP method for request type context
url: req.originalUrl, // Full URL including query params
ip: req.ip, // Client IP for security analysis
}
});
// Headers-sent protection: Prevent double response errors that crash applications
// If headers are already sent, we can only delegate to Express default error handling
if (res.headersSent) {
return next(err);
}
// Standardized error response: Consistent format for client error handling
// Always returns 500 since this middleware only handles unexpected server errors
res.status(500).json({
success: false, // Consistent boolean flag for client parsing
error: {
// Sanitized error message: Never expose internal error details
message: 'Internal Server Error',
statusCode: 500
},
// Timestamp: ISO format for consistent parsing and logging
timestamp: new Date().toISOString()
});
}
const { throwIfResNotOk, validateAndReturnResponse, isResponseOk, getResponseError } = require('./http/response-validator');
const { apiRequest, apiGet, apiPost, apiPut, apiDelete, apiPatch } = require('./http/api-request');
module.exports = {
errorHandlerMiddleware,
throwIfResNotOk,
validateAndReturnResponse,
isResponseOk,
getResponseError,
apiRequest,
apiGet,
apiPost,
apiPut,
apiDelete,
apiPatch
};