我正在创建一个Natours项目,我想分别处理开发和生产环境中发生的操作错误。
这是我的appError.js
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = AppError;
这是我的errorControllers.js
const AppError = require('../utils/appError');
const handleCastErrorDB = (err) => {
const message = `Invalid ${err.path}: ${err.value}`;
return new AppError(message, 400);
};
const sendErrorDev = (err, res) => {
res.status(err.statusCode).json({
status: err.status,
error: err,
message: err.message,
stack: err.stack,
});
};
const sendErrorProd = (err, res) => {
// Operation, trusted error: send message to Client
// console.log(err.isOperational);
if (err.isOperational) {
res.status(err.statusCode).json({
status: err.status,
message: err.message,
});
// Programming or other unkown error happened: don't leak error details
} else {
// Log error in the console
console.log('💥ERROR: ', err);
// Send error to the user
res.status(500).json({
status: 'error',
message: 'Something wrong happened.',
});
}
};
module.exports = (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || 'error';
if (process.env.NODE_ENV === 'development') {
sendErrorDev(err, res);
} else if (process.env.NODE_ENV === 'production') {
// eslint-disable-next-line node/no-unsupported-features/es-syntax
let error = { ...err };
if (error.name === 'Cast') error = handleCastErrorDB(error);
sendErrorProd(error, res);
}
next();
};
我创建了一个单独的 appError 类和 errorController 文件。因此,当发生任何错误时,根据环境是开发还是生产,都会抛出错误。但它在 sendErrorProd 函数中给出错误对象的 isOperational 属性“未定义”。
你能帮我解决我的代码中发生的错误吗?
首先,确保您真正测试的是 CastError,而不是邮递员中的其他错误。
其次,确保您处于生产环境中。
弄清楚第一步和第二步后,请尝试以下代码..
else if (process.env.NODE_ENV === 'production') {
let error = {...err};
if (err.name === 'CastError') error = handleCastErrorDB(error);
sendErrorProd(error, res);
}
请记住,您正在对内部表达错误变量进行解构,因此变量中可能会出现一些混乱。
希望它有效😀。