Errors from Mongoose do not get propagated from the router to the app layer

There is a single API application set up like so:

const express = require('express')
const app = express()
const router = require('express').Router()
...
route.post('/dogs', (req, res, next) => {
  const dog = new Dog() // defined in the actual application
  dog.validate() // error occurs here
    .then(() => {
      return res.status(201)
    })
    // [1]
})
...
app.use('/api/v1', router)
app.use(notFoundErrorHandler)
app.use(globalErrorHandler)

function notFoundErrorHandler (req, res, next) {
  res.status(404)
  res.send({error: 'Not found'})
}

function globalErrorHandler (err, req, res, next) {
  if (err) {
    res.status(err.status || 500)
    res.json({error: err.message || err})
  }
}

If there is a validation error, it does not reach the globalErrorHandler. However, catching and rethrowing the error can solve this issue [1]:

.catch(err => { return next(err) })

Is this behavior typical for Mongoose with an incomplete Promise implementation, or could it be implemented differently?

No errors are raised when using other methods such as save, find, etc.

Answer №1

It is common for issues to arise in Express that are not related to mongoose, but rather the handling of unhandled exceptions. Express does not automatically handle these exceptions, so they must be addressed explicitly. This means catching any errors in each route and passing them to next.

To simplify this process, consider creating a route manager to register each route with an action handler using a try/catch pattern.

There are various examples available, such as the following simple one that I find helpful:

 var dogHandler = require('dogHandler')

 var serverRoutes = [{
     path: "dogs",
     method: "post",
     action: dogHandler
 }]

 serverRoutes.forEach(route => {
     app[route.method](route.path, (request, response, next) => {
         route.action(request, response)
             .then(() => next)
             .catch(err => next(err));
     });
 });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Running a child process within an express js route

I have a problem where I am trying to execute a child process within my Express JS route and then return a JSON message with the output of this process as the message value. However, I am currently experiencing an issue where the stdout value is coming bac ...

Removing connected entries with pre middleware on mongoose

I currently have 3 different schemas: Building const BuildingSchema = mongoose.Schema({ address: { type: String, required: true }, numberOfFloors: { type: Number, default: 0 }, }); Apartment const RoomSchema = mongoose.Schema({ roomNumber: { type: ...

A guide on using tsc to build a local package

Unique Project Structure I have a unique monorepo structure (utilizing npm workspaces) that includes a directory called api. This api directory houses an express API written in typescript. Additionally, the api folder relies on a local package called @mya ...

Passport.js implementation in a Next.js application does not persist the user's login state when navigating between routes

I'm currently utilizing passport.js with the local-strategy for authentication in my next.js application. Data store requests and authentication are functioning properly. However, I need access to the req.user in another route to retrieve the users._ ...

What is the best way to obtain the ID following a fetch request?

I'm trying to target the ID specifically, but when I console log the data retrieved after making a fetch request, it contains more information than just the ID. I want to know how to extract and print only the ID from the response in the console. fetc ...

Encountering the "ERPROTO" error message while attempting to send an Axios request from my REST API

I have set up my API at "localhost:3000/api/shopitems" and it successfully returns the JSON data below when accessed through a browser: [ { "item_available_sizes": { "s": 1 }, "imgs": { "album": [], ...

All installations of Yeoman generators tend to throw large amounts of errors

Encountering an issue with running generators post-installation through npm. Following the installation of yoeman, grunt, bower, and various generators, any attempt to run a generator in a new filespace (e.g., yo webapp, yo backbone) triggers multiple erro ...

Relates to or possesses a singular association in Sequelize

Having two tables in my database, Users and Profile_Education. The Users data is obtained from an auth0/login form, while the Profile_Education is fetched from a node.js/express API. I am looking to establish a foreign key in Profile_Education to link it w ...

Improving the functionality of a dynamic Mongoose JS application

Hey there, I have a pretty simple question that I couldn't find an answer to on Google. So, I'm experimenting with Mongoose JS and I'm curious about how to update a live application. Let's say I've defined a schema in my node.js ...

Retrieve data from a form on the server side using an Ajax request

I am currently working on submitting form data through an Ajax call. Here is the relevant form code: <form target="_blank" id="addCaseForm" class="form-horizontal col-md-12" action="" method="POST> <div class="form-group"> <labe ...

Is there a way to ensure that the line numbers displayed for JavaScript errors in Chrome are accurate?

I suspect either my webpack configuration or my npm run dev script are causing the issue, but I'm unsure of what exactly is going wrong. While running my application in development mode, I encounter error messages like: Uncaught TypeError: this.props ...

Utilize ExpressJS to invoke a separate route from within a different route

I have a file named server.js that contains the following code: import subRouter from "./routes/sub"; import prdRouter from "./routes/prd"; const app = express(); app.use("/sub", subRouter); app.use("/prd", prdRoute ...

Pass the JSX data as JSON from the Express backend and showcase it as a component in the React frontend

I am currently developing a basic react front-end paired with an Express backend. Is it possible for me to have express send JSX data as JSON so that I can fetch it in react and utilize it as a component? Right now, I am sending JSON data and successfully ...

What is the best way to obtain logs from a NodeJs application that is being run in forever npm

Is there a way for me to view the logs of my nodejs server after using forever start server.js? I want to see what is being logged, check for any live errors, and more. I searched through their documentation but couldn't find anything helpful. I need ...

How can I easily obtain the updated version using my CLI command in NPM?

Imagine having a library that needs to be compiled with webpack, and you want to include a banner like this: // LibraryName vX.X, where vX.X represents its version. You wish to compile it using npm's preversion script as follows: "preversion": "gulp ...

Passport verification is successful during the login process, however, it encounters issues during registration

I am currently learning about passport.js and session management, and I'm in the process of implementing a local login feature on my website. Here is what I am attempting to achieve: Secret page: Authenticated users can access the secret page, while ...

Efficiently handling AWS Lambda responses by sending them before awaiting the completion of a database query using the

I am currently working on a serverless framework node js function that initializes a mysql DB and runs a query using ES6 to return an HTTP response. Is there a way for the response to be returned before the completion of the DB call? For example, in ...

"Unleashing the power of Discord.js: Crafting a dynamic command handler enhanced with collectors for smoother

I'm currently developing a Discord Bot that responds to specific commands. To simplify the process, I was considering implementing a system where the bot asks users for questions, collects their responses, and then provides the appropriate answers bas ...

Utilizing Ephemeral and MaxAge parameters in express-session for enhanced session management

I'm working on implementing the session management for an express-js application using the express-session package. Here are the specific requirements I need to meet: The cookie should be destroyed when the browser is closed. The cookie should expi ...

Exploring how to incorporate Express middleware into Firebase Functions for handling HTTPS requests

Encountering a challenge while using Express middleware with Firebase Functions. In this sample, a function is linked to the app() instance as shown below: app.get('*', (req, res) => { res.send(`Hello ${req.user.name}`); }); exports.autho ...