Express error handler failed to catch the validation error

I have a field type in my mongoose schema that is required. I've implemented a custom error handler in express like this:

const notFound = (req, res, next) => {
  const error = new Error(`Not found-${req.originalUrl}`);
  res.status(404);
  next(error);
};

const errorHandler = (err, req, res, next) => {
  
  const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
  res.status(statusCode);
  res.json({
    message: err.message,
    stack: process.env.NODE_ENV === 'production' ? null : err.stack,
  });
};

I've added the error handlers to the end of my server.js file:

app.use(notFound);
app.use(errorHandler);

However, when testing the route that posts an entry using Postman, the request gets stuck without any response. In the terminal, I see an error stating

UnhandledPromiseRejectionWarning: ValidationError: ...

Shouldn't my custom error handler catch this error?

Answer №1

Ensure that when executing a mongoose action, you are properly handling and forwarding any errors to your middleware for processing.

One way to accomplish this is by implementing code similar to the following:

example.findById(req.id, async function(err, foundRecord){
  if(err) {
    next(err);
  } else {
    ....
  }
});

Please inform me if this solution resolves your issue.

Answer №2

Try implementing a simple HttpError by following these steps:

  1. Create a file named HttpError.js:

class HttpError extends Error {
    constructor(statusCode, message = 'Internal Server Error') {
        super(message);
        this.statusCode = statusCode;
        this.isSuccess = false;
        this.isError = true;
        this.errorMessage = message;
        this.data = null;
    }
}

module.exports.HttpError = HttpError;
  1. You can create an example like: NotFoundError extending HttpError:
const { HttpError } = require('../HttpError');
class NotFoundError extends HttpError {
    constructor(message = 'Not Found') {
        super(404, message);
    }
}

module.exports.NotFoundError = NotFoundError;

In your app.js, you can handle errors as shown below:

// Handling notFoundError
app.use((req, res, next) => { throw new NotFoundError() });

// Handling unexpected errors or other errors
app.use((error, req, res, next) => {
    res.status(error.statusCode || 500).send(error);
})

If you prefer Indonesian language for tutorials ("But you don't have to listen, just understand the concept"), check out these links:

For example codes, visit this Github repository: https://github.com/12bedeveloper/basic-express

Keep learning and improving your coding skills.

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

What is the code to retrieve all _id values within an array in MongoDB?

I currently possess the following assortment: { "_id" : ObjectId("5acdb95d5ea63a27c1facf92"), "venue" : ObjectId("5acdb95d5ea63a27c1facf8c"), "author" : ObjectId("5ac8ba3582c2345af70d4658"), } { "_id" : ObjectId("5acdb95d5ea63a27c1facf93") ...

Expressjs encountering an unexpected Coffeescript error: Quote mark (') found unexpectedly

Currently working on a project using express.js, here's a snippet from my app.coffee file: ### Module dependencies. ### express = require("express") routes = require("./routes") user = require("./routes/user") http = require("http") path = require("p ...

At what point is the JavaScript function expression triggered in this code snippet?

let express = require('express') let app = express(); app.use(express.static('static')); let server = app.listen(3000, function() { let port = server.address().port; console.log("The server has started on port", port); }); I ...

Troubleshooting issue: relationship between models not functioning in Express.js when using Sequelize

I have created models Skills and Members Member Table: id username password created 1 gagandeep 99703dd91da5b0cabf496d49af0ab03c2dfe7788 2017-08-14 05:59:46 Skills Table: id member_id skill 1 1 programming 2 1 music Code: Mod ...

Utilizing Nicknames in a JavaScript Function

I'm dealing with a function that is responsible for constructing URLs using relative paths like ../../assets/images/content/recipe/. My goal is to replace the ../../assets/images section with a Vite alias, but I'm facing some challenges. Let me ...

Troubleshooting Azure node deployment: Service Unavailable error and npm WARN lifecycle warning

I am currently utilizing git to deploy a node.js application to Azure App Service. However, upon accessing the app page, I am encountering an error message that reads: Service Unavailable Furthermore, in the console, I am seeing the following error: ...

Ways to analyze users who have clicked a button

After a user registers, they are automatically taken to /proto where they can view a list of animals available for adoption. However, the challenge lies in identifying the specific user who clicked the button (as this information must be associated with th ...

Server connection failure: MongoDB is unable to establish a connection

UPDATE: After attempting different ports, terminating tasks on ports, and trying again, I am still unable to connect. Today, I embarked on a tutorial for the MERN stack but unfortunately, I am unable to establish a connection to the server. Upon using npm ...

Troubleshooting npm faq on Windows 7: How to handle 'spawn ENOENT' errors

After installing node.js on my Windows 7 using the latest installer, I encountered some issues. While I am able to call npm and node from the console (cmd or PowerShell), errors keep popping up. I have noticed many discussions about node.js on windows, bu ...

Encountered a failure while attempting to execute npm install command for Express

Having trouble with the npm install express command due to an error? Here's the error message: $ npm install express npm ERR! fetch failed https://registry.npmjs.org/debug/-/debug-2.1.0.tgz npm ERR! fetch failed https://registry.npmjs.org/etag/-/etag ...

I encountered an error message saying "TypeError: response.json is not a function" while attempting to make a request using fetch in a project involving ReactJS and Node

Currently, I am in the process of developing a webpage using reactjs and have set up a simple REST api/database with nodejs. My main focus right now is on properly utilizing this API from the front end. The objective was to send a JSON payload containing { ...

Transferring information between Express and React through the Contentful API

I have embarked on a journey to explore Contentful's headless CMS, but I am encountering a challenge with their API client. My goal is to combine Express with React for server-side rendering, and I am utilizing this repository as my starting point. S ...

sending back a JSON object that appears empty, despite actually containing data

I'm facing an issue where I am attempting to send a json response to my react client, containing a list of songs (objects). However, the json returns as an empty array. This is how I am fetching the data: let songs = []; fetch("https://api.spotify. ...

Producing two observables, handling the output, and subsequently emitting a different one

I have been assigned a task that involves working with multiple observables in a specific way: The goal is to emit two observables (obs1 & obs2), process their results, and then call another observable (obs3). It's important that while processing the ...

Nestjs: Step-by-step guide to removing a specific application from a Nestjs monorepo using nest/cli

Is there a method to delete a specific app within a nestjs monorepo using the nest/cli? I have searched through the documentation and developer forums but cannot seem to find a solution. ...

Issue with npm not detecting .npmrc configuration file

Struggling with the installation of a library from a private repository using npm? The setup I have is as follows: OSX Mavericks 10.9.3 Node v0.10.28 npm 1.4.10 (switched from 1.4.13 but still facing issues) I'm executing this from my home directory ...

Setting up a local development environment for AngularJS

I have been using the boilerplate https://github.com/node90/angular-starter as a foundation for my projects. However, I've noticed that the repository utilizes gulp to consolidate the js files in the 'app' folder into the 'public/js&apo ...

Verifying an array of objects in NodeJS

Here is an example of the array I am working with: settings: [ { key: 'maxImageSize', value: '512' }, { key: 'maxFileSize', value: '2048' }, { key: 'searchResultsLimit', value: '10' ...

Broadcast to every socket except the one that is malfunctioning on Socket.io

My current task involves sending a message to all connected sockets on my server using socket.io. The code I have written so far looks like this: if(electionExists) { var connectedClients = io.sockets.adapter.rooms[electionRequested].sockets; ...

I'm encountering an issue in my server.js file where I am unable to read the property 'collection' as it is undefined

I have encountered an error in my code: /home/ubuntu/workspace/server.js:43 db.collection('quotes').find().toArray(function(err, results) { ^ TypeError: Cannot read property 'collection' of undefined at Object.<anonymous> ( ...