first commit
This commit is contained in:
50
src/middleware/error.middleware.ts
Normal file
50
src/middleware/error.middleware.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import logger from '../utils/logger.js';
|
||||
import type { ApiResponse } from '../types/index.js';
|
||||
|
||||
/**
|
||||
* Global Error Handler Middleware
|
||||
*/
|
||||
export function errorHandler(
|
||||
error: Error,
|
||||
req: Request,
|
||||
res: Response,
|
||||
_next: NextFunction
|
||||
): void {
|
||||
logger.error('Unhandled error', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
path: req.path,
|
||||
method: req.method,
|
||||
});
|
||||
|
||||
const response: ApiResponse<never> = {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'INTERNAL_ERROR',
|
||||
message: 'An unexpected error occurred. Please try again later.',
|
||||
},
|
||||
};
|
||||
|
||||
res.status(500).json(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 404 Not Found Handler
|
||||
*/
|
||||
export function notFoundHandler(
|
||||
req: Request,
|
||||
res: Response
|
||||
): void {
|
||||
const response: ApiResponse<never> = {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'NOT_FOUND',
|
||||
message: `Endpoint ${req.method} ${req.path} not found`,
|
||||
},
|
||||
};
|
||||
|
||||
res.status(404).json(response);
|
||||
}
|
||||
|
||||
export default errorHandler;
|
||||
Reference in New Issue
Block a user