Home > Software engineering >  Program completely exits after Mongoose receives an error. No method of error handling prevents this
Program completely exits after Mongoose receives an error. No method of error handling prevents this

Time:08-17

Mongoose version

6.3.4

Node.js version

18.6.0

MongoDB version

4.4

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

20.04

Issue

To summarize this issue, it's basically causing my program to exit or crash when an error is thrown by mongoose. When I first encountered this error, I tried fitting my program with more error handling. However, after all the effort the program still crashes from an error that is thrown. I think it's because somewhere where an error isn't handled but I can't seem to find where that is.

This is my database module, and the way I error handle.

import { Console } from 'console'
import mongoose from 'mongoose'
import Logger from '../util/logger'

const logger = new Logger(`Worker/${process.pid}/database/site`)

const schemas = {
  sitemeta: new mongoose.Schema({
    setting: { type: String },
    data: { type: Object }
  }, { collection: 'site-meta' }),
  project: new mongoose.Schema({
    project_name: { type: String },
    description: { type: String },
    project_short_name: { type: String },
    side_project: { type: Boolean },
    project_body: { type: String },
    thumbnail_source: { type: String }
  }, { collection: 'projects' }),
  admin: new mongoose.Schema({
    key_hash: { type: String },
    key_identifier: { type: String }
  }, { collection: 'admins' })
}

async function dbConnect () {
  try {
    await mongoose.connect(process.env.MONGODB!, { dbName: 'site' })
    mongoose.connection
      .on('error', () => logger.error('db error occured'))
      .once('open', () => logger.log('Connected to database'))
  } catch {
    logger.error('DB connect fail')
  }
}

dbConnect()

const SiteMeta = mongoose.model('site-meta', schemas.sitemeta)
const Project = mongoose.model('projects', schemas.project)
const Admin = mongoose.model('admins', schemas.admin)

export { SiteMeta, Project, Admin }

In order to test this, I an purposely shutting off my MongoDB server instance and then starting the app and watching the console. This is the error that I get:

/home/myusr/website-core/node_modules/mongodb/src/sdam/topology.ts:606
        const timeoutError = new MongoServerSelectionError(
                             ^
MongoServerSelectionError: connect ECONNREFUSED MYIP:PORT
    at Timeout._onTimeout (/home/myusr/website-core/node_modules/mongodb/src/sdam/topology.ts:606:30)
    at listOnTimeout (node:internal/timers:564:17)
    at processTimers (node:internal/timers:507:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'wonik-server.ddns.net:4823' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}

However, "DB connect fail" is being written to the console from the catch on line 33. Which means it's at least handling the error. However for some reason the app still crashes.

Full log:

[ERROR] [08/08/2022, 03:46:14][wonik-website-core/Worker/8955/database/site] DB connect fail
/home/myusr/website-core/node_modules/mongodb/src/sdam/topology.ts:606
        const timeoutError = new MongoServerSelectionError(
                             ^
MongoServerSelectionError: connect ECONNREFUSED MYIP:PORT
    at Timeout._onTimeout (/home/myusr/website-core/node_modules/mongodb/src/sdam/topology.ts:606:30)
    at listOnTimeout (node:internal/timers:564:17)
    at processTimers (node:internal/timers:507:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'wonik-server.ddns.net:4823' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}
[nodemon] app crashed - waiting for file changes before starting...

I need help finding a solution to error handling which prevents mongoose from crashing my app. Thanks in advance!

CodePudding user response:

Node.js 18.6.0 is not kind with error handling for mongoose. Try switching to Node.js LTS to prevent unexpected crashes from errors.

  • Related