All checks were successful
Deploy to Web Server flyer-crawler.projectium.com / deploy (push) Successful in 1m8s
27 lines
998 B
TypeScript
27 lines
998 B
TypeScript
// src/middleware/errorHandler.ts
|
|
import { Request, Response, NextFunction } from 'express';
|
|
import { logger } from '../services/logger.server';
|
|
|
|
interface HttpError extends Error {
|
|
status?: number;
|
|
// You can add other custom properties like 'code' if needed
|
|
}
|
|
|
|
export const errorHandler = (err: HttpError, req: Request, res: Response, next: NextFunction) => {
|
|
// If the response headers have already been sent, we must delegate to the default Express error handler.
|
|
if (res.headersSent) {
|
|
return next(err);
|
|
}
|
|
|
|
// Use the status code from the error if it exists, otherwise default to 500.
|
|
const statusCode = err.status || 500;
|
|
|
|
// Log the full error details for debugging, especially for server errors.
|
|
if (statusCode >= 500) {
|
|
logger.error('Unhandled API Error:', { error: err.stack || err.message, path: req.path, method: req.method });
|
|
}
|
|
|
|
res.status(statusCode).json({
|
|
message: statusCode >= 500 ? 'An unexpected server error occurred.' : err.message,
|
|
});
|
|
}; |