我正在开发 express 应用程序,当我指定所有路由和中间件后,在 server.js 文件的末尾添加了以下内容:
问题是,当使用
// Log errors
app.use(function (err, req, res, next) {
logger.error(err.stack);
if(process.env.NODE_ENV === 'production')
return res.status(500).send('Something broke!');
next(err);
});
// Start server
app.listen(port, () => {
logger.info('Server is up on port ' + port);
});
这样做的目的是在生产环境中捕获所有错误,避免向客户端泄露敏感数据。
我在其中一个控制器中有这段代码:
const createHTTPError = require('http-errors')
async function(req, res, next) {
try {
invoice = await Invoice.create({
// data
});
}catch (e) {
if(e instanceof Sequelize.ValidationError){
logger.error(e);
return next(createHTTPError(400, 'Validation did not pass: ' + e.message));
}
}
}
问题是,当使用
http-errors
对象调用 next()
时,它会冒泡到我的通用错误处理程序,但信息会丢失,在其中,err 对象是一个简单的 Error
实例,具有以下这些参数:message = "Validation did not pass: notNull Violation: invoice.clientEmail cannot be null"
name = "BadRequestError"
stack = "BadRequestError: Validation did not pass: notNull Violation: invoice.clientEmail cannot be null\n at module.exports (/home/XXXX/create-new-invoice.js:109:33)"
错误代码编号丢失。错误对象类型丢失(好吧,在名称中转换为字符串)。
我该怎么办?如果我删除我的捕获所有异常的语句,那么就有泄露一些敏感信息的风险。谢谢。