refactor(utils): Extract utilities from server.js
- Create src/utils/http.js - fetchT and HTTP helpers - Create src/utils/logging.js - Structured logging and error logging - Create src/utils/responses.js - Standard API responses - Create src/utils/async-handler.js - Async wrapper with error handling - Create src/utils/index.js - Consolidated exports Removes scattered helper functions from server.js
This commit is contained in:
30
dashcaddy-api/src/utils/async-handler.js
Normal file
30
dashcaddy-api/src/utils/async-handler.js
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Async handler wrapper - Eliminates try/catch boilerplate
|
||||
*/
|
||||
const { AppError } = require('../../errors');
|
||||
|
||||
/**
|
||||
* Wrap async route handlers - catches errors and logs them
|
||||
*/
|
||||
function asyncHandler(logError, fn, context) {
|
||||
return async (req, res, next) => {
|
||||
try {
|
||||
await fn(req, res, next);
|
||||
} catch (error) {
|
||||
// Let typed errors propagate to global error handler
|
||||
if (error instanceof AppError) {
|
||||
return next(error);
|
||||
}
|
||||
|
||||
await logError(context || req.path, error);
|
||||
|
||||
if (!res.headersSent) {
|
||||
const { errorResponse } = require('./responses');
|
||||
const { safeErrorMessage } = require('./logging');
|
||||
errorResponse(res, 500, safeErrorMessage(error));
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { asyncHandler };
|
||||
Reference in New Issue
Block a user