backend: Add middleware to handle JSON syntax errors in request bodies

This commit is contained in:
Carlos Santos 2025-04-10 16:44:42 +02:00
parent 3731d648fc
commit c090e255c2
2 changed files with 25 additions and 0 deletions

View File

@ -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);
}
};

View File

@ -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