This commit is contained in:
Matthias Hochmeister
2026-02-23 17:08:58 +01:00
commit f09748f4a1
97 changed files with 17729 additions and 0 deletions

View File

@@ -0,0 +1,66 @@
import { Request, Response, NextFunction } from 'express';
import logger from '../utils/logger';
export class AppError extends Error {
statusCode: number;
isOperational: boolean;
constructor(message: string, statusCode: number = 500) {
super(message);
this.statusCode = statusCode;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
export const errorHandler = (
err: Error | AppError,
req: Request,
res: Response,
_next: NextFunction
): void => {
if (err instanceof AppError) {
logger.error('Application Error', {
message: err.message,
statusCode: err.statusCode,
stack: err.stack,
path: req.path,
method: req.method,
});
res.status(err.statusCode).json({
status: 'error',
message: err.message,
});
return;
}
// Handle unexpected errors
logger.error('Unexpected Error', {
message: err.message,
stack: err.stack,
path: req.path,
method: req.method,
});
res.status(500).json({
status: 'error',
message: process.env.NODE_ENV === 'production'
? 'Internal server error'
: err.message,
});
};
export const notFoundHandler = (req: Request, res: Response): void => {
res.status(404).json({
status: 'error',
message: `Route ${req.originalUrl} not found`,
});
};
export const asyncHandler = (fn: Function) => {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};