我在 next.js 应用程序中使用 next-connect 来运行服务器端代码。我正在使用自定义错误中间件,但它抛出错误为
res.status is undefined
这是我的错误中间件
export const errorMiddleWare = (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
let error = { ...err };
error.message = err.message;
if (err.name === 'CastError') {
const message = 'Resource not found for given' + err.path;
error = new ErrorHandler(message, 400);
}
if (err.name === 'ValidationError') {
const message = Object.values(err.errors).map((e) => e.message);
error = new ErrorHandler(message, 400);
}
res.status(err.statusCode).json({
error,
message: error.message,
stack: error.stack,
});
};
我在 api 文件夹内的页面中的路线
import nc from 'next-connect';
import connectDb from '../../../config/dbconnect';
import { getAllProducts } from '../../../controllers/productController';
import { errorMiddleWare } from '../../../middlewares/error';
const router = nc();
connectDb();
//Routes
router.use(errorMiddleWare).get(getAllProducts);
export default router;