qerrors
Version:
Intelligent error handling middleware with AI-powered analysis, environment validation, caching, and production-ready logging. Provides OpenAI-based error suggestions, queue management, retry mechanisms, and comprehensive configuration options for Node.js
55 lines (52 loc) • 2.79 kB
Plain Text
*
* Rationale: API responses should be consistent and safe. This function ensures
* all JSON responses follow the same pattern and gracefully handles any
* serialization errors that might occur with complex objects. The logging helps
* with debugging by showing exactly what was sent to clients, which is crucial
* for API gateway functionality where responses pass through multiple layers.
*
* {Object} res - Express response object
* {number} statusCode - HTTP status code to send
* {Object} payload - Data to send as JSON response
*/
// sendJsonResponse provided by qgenutils handles JSON output and logging
/**
* Standardized error handling for controller functions
*
* Rationale: Controllers throughout the application need consistent error handling.
* This function provides a single point of error logging and response formatting,
* ensuring clients always receive meaningful error messages while maintaining
* detailed logging for debugging.
*
* The conditional request logging allows this function to be used in both
* request-based contexts (normal API calls) and non-request contexts (background tasks).
*
* The headersSent check prevents Express errors when trying to send multiple responses,
* which can happen in complex middleware chains or async error scenarios.
*
* @param {Object} res - Express response object
* @param {Error} error - The error object that occurred
* @param {string} message - Human-readable error message for the client
* @param {Object} [req] - Optional Express request object for additional context
*/
function handleControllerError(res, error, message, req){ // unified error response
console.log(`handleControllerError is running with ${message}`); // Log error handling initiation
try {
if(req){
qerrors(error, message, req); // Log error with full request context for better debugging
} else {
qerrors(error, message); // Log error without request context (background operations)
}
// Only send response if headers haven't been sent already
// This prevents "Cannot set headers after they are sent" errors
if(!res.headersSent){
sendJsonResponse(res, 500, { error: message }); // Send standardized error response
}
console.log(`handleControllerError has run resulting in a final value of ${message}`); // Log completion
} catch(err){
// Handle meta-errors (errors in error handling itself)
// This provides a fallback to prevent complete system failure
qerrors(err, 'handleControllerError', { message }); // Log the meta-error
}
}
module.exports = { sendJsonResponse, handleControllerError }; // Export utility functions for use across controllers