How to set up Middleware error handling in Node.js, express & MongoDB

How to set up Middleware error handling in Node.js, express & MongoDB

Introduction

This JavaScript file defines two middleware functions for an Express.js application: notFound and errorHandler.

  1. notFound: This middleware function is used to handle 404 errors, which occur when a client tries to access a route that does not exist. It creates a new Error object with a message indicating the original URL that was not found, sets the response status code to 404, and passes the error to the next middleware function.

  2. errorHandler: This middleware function is used to handle all other types of errors. It first checks the response's status code. If it's 200 (which means OK), it changes it to 500 (which means Internal Server Error). Then, it checks if the error is a 'CastError' and the kind is 'ObjectId', which usually means that the client provided an invalid ID for a resource. In this case, it sets the status code to 400 (Bad Request) and changes the error message. Finally, it sends a JSON response with the error message and, if the application is not in production, the error stack trace.

These middleware functions are exported at the end of the file, so they can be imported and used in other parts of the application.

How to Set up?

If you read the above guide then now you are able to do this.

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

const errorHandler = (err, req, res, next) => {
    // sometimes error status code is 200 when we create menually, so we set it to 500 if it is 200
    const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
    const message = err.message;

    if (err.name === 'CastError' && err.kind === 'ObjectId') {
        res.status(400);
        message = 'Resources not found';
    }  

    res.status(statusCode).json({
        message,
        stack: process.env.NODE_ENV === 'production' ? null : err.stack
});

}

export { notFound, errorHandler };

How to use it in your Application?

Now you can import the error and use it in your main file, in my case server.js for you this can be different. Look at the following code

import express from 'express';
import dotenv from 'dotenv';
dotenv.config();
import { notFound, errorHandler } from './middleware/errorMiddleware.js';
import connectDB from './db/db.js';
const PORT = process.env.PORT || 5000;
import userRoutes from './routes/userRoutes.js';

connectDB();

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true })); //  this will allow us to accept json data in the body like `form data`

app.use('/api/users', userRoutes);

app.get('/', (req, res) => {
    res.send('Hello World!');
});

// Error middleware
app.use(notFound);
app.use(errorHandler);

app.listen(PORT, () => 
console.log(`Server running on port: http://localhost:${PORT}`)
);

Did you find this article valuable?

Support Shivam Sharma by becoming a sponsor. Any amount is appreciated!