[added] - new routes

This commit is contained in:
Swapnil Bendal
2024-12-18 15:08:10 +05:30
parent ac0d3012c7
commit b8feb4bf89
9 changed files with 64 additions and 27 deletions

View File

@@ -40,36 +40,44 @@ class error {
static errorHandler(
err: ApiError,
req: Request,
res: Response
res: Response,
_next: NextFunction // Retain this even if unused
): void {
let { statusCode, message } = err;
// Production environment: Ensure only operational errors are shown
if (config.env === 'production' && !err.isOperational) {
// Extract error details with fallback defaults
let { statusCode = 500, message = "Internal server error" } = err;
// Production: Ensure only operational errors reveal their messages
if (config.env === "production" && !err.isOperational) {
statusCode = 500;
message = "Internal server error";
message = "An unexpected error occurred";
}
// Attach error message to response locals for potential templating
res.locals.errorMessage = err.message;
// Response structure
// Construct the response payload
const response = {
code: statusCode,
message,
...(config.env === 'development' && { stack: err.stack })
...(config.env === "development" && err.stack && { stack: err.stack }), // Include stack trace only in development
...(err.errors && { errors: err.errors.map((e: Error) => e.message) }), // Include nested validation errors if any
};
// Log error in development
if (config.env === 'development') {
logger.error(err);
}
// Ensure the response is sent
res.status(statusCode).send(response);
// Don't call next() unless you want to propagate the error further
// If this is the final middleware, remove next()
// Log the error in all environments
logger.error({
message: err.message,
stack: err.stack,
statusCode,
errors: err.errors || [],
});
// Send the response
res.status(statusCode).json(response);
// Do not call `next()` here, as this is the final error handler.
}
}
export default error;