Consolidate response helpers and error logger to single modules
CI / Test & Lint (push) Has been cancelled
CI / Security audit (push) Has been cancelled

Two cleanups in one pass for the v1.14.0 'works on any platform' theme:

1. Response helpers — merged src/utils/responses.js and the root-level
   response-helpers.js into a single module at src/utils/responses.js.
   The old module had a richer set (created, noContent, validationError,
   unauthorized, forbidden, notFound, conflict) and is now re-exported
   from the new location. Updated 15 routes to import from
   src/utils/responses and deleted the root response-helpers.js.

2. Error logger — error-handler.js now uses the unified
   src/utils/logging.js#logError (same one src/app.js uses), so all errors
   go to one log file with one rotation policy. Removed the dead
   asyncHandler export (the real one is in src/utils/async-handler.js
   and is used everywhere). Deleted the legacy error-logger.js.

Both are invisible to users — same HTTP response shapes, same log file
path, same error format. Internal-only refactor.
This commit is contained in:
Hermes
2026-06-10 21:37:55 -07:00
parent caa09dcebe
commit 11cfb8c26a
22 changed files with 167 additions and 318 deletions
+30 -27
View File
@@ -1,66 +1,70 @@
/**
* DashCaddy Error Handler Middleware
* Centralizes error handling logic to eliminate duplicate catch blocks
*
* Logging: this middleware uses the unified logError from src/utils/logging.js
* (same one src/app.js uses), so all errors go to one log file. The legacy
* ./error-logger.js and its ./error.log file have been retired.
*/
const path = require('path');
const { AppError } = require('./errors');
const { logError } = require('./error-logger');
const { LIMITS } = require('./constants');
const { logError: unifiedLogError, safeErrorMessage } = require('./src/utils/logging');
/**
* Async route handler wrapper
* Automatically catches errors and passes to error middleware
* Usage: app.get('/route', asyncHandler(async (req, res) => { ... }))
*/
function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}
const ERROR_LOG_FILE = path.join(__dirname, 'error.log');
const MAX_ERROR_LOG_SIZE = LIMITS.ERROR_LOG_SIZE;
/**
* Global error handling middleware
* MUST be registered after all routes in server.js
*/
function errorMiddleware(err, req, res, next) {
// Log all errors with request context
logError(req.path, err, {
method: req.method,
ip: req.ip,
userId: req.user?.id,
body: req.body
});
// Log all errors with request context (unified, same file the rest of the app uses)
unifiedLogError(
ERROR_LOG_FILE,
MAX_ERROR_LOG_SIZE,
req.path,
err,
{
method: req.method,
ip: req.ip,
userId: req.user?.id,
body: req.body
}
).catch(e => console.error('Failed to write to error log:', e.message));
// Determine if this is an operational error (AppError) or programming error
const isOperational = err.isOperational || err instanceof AppError;
// Status code
const statusCode = err.statusCode || 500;
// Error code (DC-XXX format)
const code = err.code || `DC-${statusCode}`;
// Build response
const response = {
success: false,
error: isOperational ? err.message : 'Internal server error',
error: isOperational ? safeErrorMessage(err) : 'Internal server error',
code
};
// Add optional fields if present
if (err.requiresTotp) response.requiresTotp = true;
if (err.retryAfter) response.retryAfter = err.retryAfter;
if (err.field) response.field = err.field;
if (err.resource) response.resource = err.resource;
if (err.details && Object.keys(err.details).length > 0) response.details = err.details;
// Development mode: include stack trace
if (process.env.NODE_ENV === 'development') {
response.stack = err.stack;
}
// Send response
res.status(statusCode).json(response);
// For non-operational errors, log as fatal
if (!isOperational) {
console.error('FATAL: Non-operational error detected', {
@@ -81,7 +85,6 @@ function notFoundHandler(req, res, next) {
}
module.exports = {
asyncHandler,
errorMiddleware,
notFoundHandler
};