tinfo-web-server / middleware /errorMiddleware.js
Faridaqurr
initial backend
e8c33fa
Raw
History Blame Contribute Delete
1.7 kB
const { env } = require('../configs/env');
const { logError } = require('../utils/errorLogger');
const HTTP_CODE_MAP = {
400: 'BAD_REQUEST',
401: 'UNAUTHORIZED',
403: 'FORBIDDEN',
404: 'NOT_FOUND',
409: 'CONFLICT',
413: 'PAYLOAD_TOO_LARGE',
422: 'UNPROCESSABLE_ENTITY',
429: 'RATE_LIMIT_EXCEEDED',
503: 'SERVICE_UNAVAILABLE',
};
const getCode = (statusCode) =>
HTTP_CODE_MAP[statusCode] || (statusCode >= 500 ? 'INTERNAL_SERVER_ERROR' : 'REQUEST_FAILED');
const errorHandler = (err, req, res, _next) => {
let statusCode = err.statusCode || err.status || (res.statusCode === 200 ? 500 : res.statusCode);
let message = err.message || 'Something went wrong';
if (err?.name === 'MulterError') {
statusCode = 400;
if (err.code === 'LIMIT_FILE_SIZE') {
message = 'File is too large. Please check the maximum upload size for this action.';
} else if (err.code === 'LIMIT_UNEXPECTED_FILE') {
const field = String(err.field || '').trim();
message = field
? `Unexpected upload field: ${field}. Please upload the file using the correct form field.`
: 'Unexpected upload field. Please upload the file using the correct form field.';
}
}
const code = getCode(statusCode);
if (statusCode >= 500) {
logError(err, { req, statusCode, code });
if (env.isProduction) {
message = 'An internal error occurred. Please try again later.';
}
}
res.status(statusCode).json({ success: false, message, code });
};
const notFound = (req, res) => {
res.status(404).json({
success: false,
message: `Not found: ${req.originalUrl}`,
code: 'NOT_FOUND',
});
};
module.exports = { errorHandler, notFound };