Back to Courses

World's Best MERN Stack Course

#16: Express.js Error Handling: A Deep Dive into Error Middleware Implementation in Our MERN App

Welcome, Explore the world of Express.js error handling in our MERN application tutorial! Where we will see how to effectively manage errors with step-by-step guidance on implementing error middleware.

πŸ“š Resources mentioned in our MERN Course & Don't forget to watch πŸ‘‡

πŸ‘‰ MongoDB Course: https://youtu.be/rU9ZODw5yvU

error-middleware.js

const errorMiddleware = (err, req, res, next) => {
  const status = err.status || 500;
  const message = err.message || "Backend Error";
  const extraDetails = err.extraDetails || "Error from the Backend";

  console.error(
    `[${req.method}]  ${req.path} >> StatusCode:: ${status}, Message:: ${extraDetails} `
  );

  return res.status(status).json({ message, extraDetails });
};

module.exports = errorMiddleware;

also add the middleware at the bottom in our server,.js file

require("dotenv").config();
const express = require("express");
const app = express();
const router = require("./routes/auth-route");
const connectDb = require("./utils/db");
const errorMiddleware = require("./middlewares/error-middleware");

// to get the json data in express app.
app.use(express.json());

// Mount the Router: To use the router in your main Express app, you can "mount" it at a specific URL prefix
app.use("/api/auth", router);

app.use(errorMiddleware);

const PORT = 5000;
connectDb().then(() => {
  app.listen(PORT, () => {
    console.log(`server is running at port: ${PORT}`);
  });
});