diff --git a/backend/src/middlewares/content-type.middleware.ts b/backend/src/middlewares/content-type.middleware.ts index ff18593..0b14168 100644 --- a/backend/src/middlewares/content-type.middleware.ts +++ b/backend/src/middlewares/content-type.middleware.ts @@ -16,3 +16,26 @@ export const mediaTypeValidatorMiddleware = (req: Request, res: Response, next: next(); }; + +/** + * Express middleware that handles JSON syntax errors in request bodies. + * If a SyntaxError with status 400 is detected and contains a 'body' property, + * it responds with a 400 Bad Request status and a JSON error message. + * Otherwise, it passes the error to the next middleware in the chain. + * + * @param err - The error object that was caught + * @param req - The Express request object + * @param res - The Express response object + * @param next - Express next function to continue to the next middleware + */ +export const jsonSyntaxErrorHandler = (err: any, req: Request, res: Response, next: NextFunction): void => { + // This middleware handles JSON syntax errors + if (err instanceof SyntaxError && (err as any).status === 400 && 'body' in err) { + res.status(400).json({ + error: 'Bad Request', + message: 'Malformed Body' + }); + } else { + next(err); + } +}; diff --git a/backend/src/server.ts b/backend/src/server.ts index 0e53b26..ac791c2 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -27,6 +27,7 @@ import { } from './routes/index.js'; import { internalParticipantsRouter } from './routes/participants.routes.js'; import cookieParser from 'cookie-parser'; +import { jsonSyntaxErrorHandler } from './middlewares/content-type.middleware.js'; const createApp = () => { const app: Express = express(); @@ -44,6 +45,7 @@ const createApp = () => { // Serve static files app.use(express.static(publicFilesPath)); app.use(express.json()); + app.use(jsonSyntaxErrorHandler); app.use(cookieParser()); // Public API routes