Home > OS >  errorMiddleware not working as expected in express
errorMiddleware not working as expected in express

Time:02-21

My errorHandler middleware is not showing up the response. Instead of giving the error in json format as I have coded, it still shows the error in html format. Where did i go wrong?

app.js

import express from "express";
import dotenv from "dotenv";
import connectDB from "./config/db.js";
import colors from "colors";
import productRoutes from "./routes/productRoutes.js";
import errorHandler from "./middlewares/errorMiddleware.js";

dotenv.config();

// Connecting to MongoDB
connectDB();

// Express specific
const app = express();

// Middlewares
app.use(errorHandler);

app.use("/api/products", productRoutes);

app.use("/api/products/:id", productRoutes);

const PORT = process.env.PORT || 5000;

app.listen(
  PORT,
  console.log(
    `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
  )
);

errorMiddleware.js

const errorHandler = (err, req, res, next) => {
  const statusCode = res.statusCode === 200 ? 500 : res.statusCode; //we sometimes get 200 code (ok) even if its error. 500 means server error
  res.status(statusCode);
  res.json({
    message: err.message,
    stack: process.env.NODE_ENV === "production" ? null : err.stack,
  });
};

export default errorHandler;

Output: enter image description here

expected Output:

{
   message: ...
   stack: ...
}

CodePudding user response:

You define error-handling middleware last, after other app.use() and routes call

source

Here is the basic working example

import express from "express";

const app = express();

app.use('/api/products', (req, res) => {
  throw new Error('Triggers an error');
});

// Do other routes here and keep error handling below.

app.use((err, req, res, next) => {
  res.status(res.statusCode);
  res.json({
    message: err.message,
    stack: process.env.NODE_ENV === "production" ? null : err.stack,
  });
})

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`);
});

Your only mistake is defining the middleware order.

  • Related