errorMiddleware 在 express 中没有按预期工作

errorMiddleware not working as expected in express

我的 errorHandler 中间件没有显示响应。 它没有像我编码的那样以 json 格式给出错误,它仍然以 html 格式显示错误。我哪里错了?

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;

输出:

预期输出:

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

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

source

这是基本的工作示例

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}`);
});

您唯一的错误是定义了中间件顺序。