🪂 fix: Handle MongoDB Connection Errors to Prevent Process Crashes (#11809)

* fix: handle MongoDB connection errors to prevent process crashes

Add mongoose.connection.on('error') listener in connect.js to catch
connection-level errors emitted by MongoDB driver's SDAM monitoring.
Without this listener, these errors become uncaught exceptions per
Node.js EventEmitter behavior.

Also add MongoDB error patterns to the uncaughtException handler in
server/index.js as defense-in-depth, following the same pattern used
for GoogleGenerativeAI, Meilisearch, and OpenAI errors.

Fixes #11808

* style: fix prettier formatting in uncaughtException handler

* refactor: move error listener to module level

* fix: use precise MongoDB error matching in uncaughtException handler

* fix: replace process.exit(1) with graceful error logging

Instead of maintaining a growing list of error patterns that should
not crash the process, invert the default behavior: log all unhandled
errors and keep running. The existing specific handlers are preserved
for their contextual log messages.

This prevents process crashes from any transient error (MongoDB timeouts,
network issues, third-party library bugs) without needing to add new
patterns each time a new error type is encountered. Unnecessary restarts
are expensive as they trigger full Meilisearch re-syncs under load.

* fix: address review feedback

- connect.js: pass full error object to logger instead of just message
- server/index.js: add optional chaining for nullish err
- server/index.js: make crash-on-unknown-error opt-in via
  CRASH_ON_UNCAUGHT_EXCEPTION env var (defaults to graceful logging)

* fix: rename to CONTINUE_ON_UNCAUGHT_EXCEPTION, default to exit

---------

Co-authored-by: Feng Lu <feng.lu@kindredgroup.com>
This commit is contained in:
MyGitHub 2026-02-16 22:23:59 +01:00 committed by GitHub
parent 3c844c9cc6
commit 413c2bc076
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 13 additions and 0 deletions

View file

@ -40,6 +40,10 @@ if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}
mongoose.connection.on('error', (err) => {
logger.error('[connectDb] MongoDB connection error:', err);
});
async function connectDb() {
if (cached.conn && cached.conn?._readyState === 1) {
return cached.conn;

View file

@ -251,6 +251,15 @@ process.on('uncaughtException', (err) => {
return;
}
if (isEnabled(process.env.CONTINUE_ON_UNCAUGHT_EXCEPTION)) {
logger.error('Unhandled error encountered. The app will continue running.', {
name: err?.name,
message: err?.message,
stack: err?.stack,
});
return;
}
process.exit(1);
});