From 77884c14aa71ce68d914d9a28466e7a3a7cfba87 Mon Sep 17 00:00:00 2001 From: Odrec <9385209+Odrec@users.noreply.github.com> Date: Wed, 19 Mar 2025 08:27:58 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix:=20Prevent=20Crash=20on=20Du?= =?UTF-8?q?plicate=20Message=20ID=20(#6392)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: prevent crash on duplicate message ID Added error handling for MongoDB error code 11000 (duplicate key error) in saveMessage function. This prevents the application from crashing when trying to save messages with duplicate IDs, which can happen during aborted requests. Now logs a warning and continues execution safely. Closes: #5774 Closes: #5776 * fix: address ESLint issues in Message.js --------- Co-authored-by: odrec --- api/models/Message.js | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/api/models/Message.js b/api/models/Message.js index e651b20ad0..58068813ef 100644 --- a/api/models/Message.js +++ b/api/models/Message.js @@ -71,7 +71,42 @@ async function saveMessage(req, params, metadata) { } catch (err) { logger.error('Error saving message:', err); logger.info(`---\`saveMessage\` context: ${metadata?.context}`); - throw err; + + // Check if this is a duplicate key error (MongoDB error code 11000) + if (err.code === 11000 && err.message.includes('duplicate key error')) { + // Log the duplicate key error but don't crash the application + logger.warn(`Duplicate messageId detected: ${params.messageId}. Continuing execution.`); + + try { + // Try to find the existing message with this ID + const existingMessage = await Message.findOne({ + messageId: params.messageId, + user: req.user.id, + }); + + // If we found it, return it + if (existingMessage) { + return existingMessage.toObject(); + } + + // If we can't find it (unlikely but possible in race conditions) + return { + ...params, + messageId: params.messageId, + user: req.user.id, + }; + } catch (findError) { + // If the findOne also fails, log it but don't crash + logger.warn(`Could not retrieve existing message with ID ${params.messageId}: ${findError.message}`); + return { + ...params, + messageId: params.messageId, + user: req.user.id, + }; + } + } + + throw err; // Re-throw other errors } }