add error handling and more tests

This commit is contained in:
jwinterm
2025-09-29 11:20:11 -04:00
parent c7cbdff021
commit 95711b9d26
14 changed files with 582 additions and 519 deletions
+36
View File
@@ -0,0 +1,36 @@
const { normalizeError, isTrustedError } = require('../utils/errors');
module.exports = function createErrorMiddleware({ logger = console } = {}) {
return function errorMiddleware(err, req, res, next) { // eslint-disable-line no-unused-vars
const normalized = normalizeError(err);
const status = normalized.statusCode || 500;
const response = {
error: normalized.code || 'INTERNAL_ERROR',
message: normalized.safeMessage || 'An unexpected error occurred.'
};
if (normalized.details) {
response.details = normalized.details;
}
if (logger && typeof logger.error === 'function') {
const logPayload = {
message: normalized.message,
code: normalized.code,
status,
path: req.path,
method: req.method,
trusted: isTrustedError(normalized)
};
if (normalized.details) {
logPayload.details = normalized.details;
}
if (normalized.cause) {
logPayload.cause = normalized.cause?.message || normalized.cause;
}
logger.error('Request failed', logPayload);
}
res.status(status).json(response);
};
};