如何通过使用Node.js捕获错误和res.发送错误消息到客户端?



在使用Node.js从数据库中搜索数据后试图捕获错误。但是,当发生错误时,服务器总是向客户端发送{errormsg: null}。我希望在errormsg json中有一个详细的解释。

router.get('/testing', (req, res) => { 
var db = req.db;
var col = db.get('collection'); 
col.find({})
.then((docs) => {res.json(docs);})
.catch((error) => {res.json({errormsg:error});
}); 
});

错误对象的许多属性是不可枚举的,因此不会在JSON中显示(是的,这通常很痛苦)。

你可以自己看到如果你只是运行这个简单的nodejs程序:

try {
throw new Error("stuff happened");
} catch (e) {
console.log(JSON.stringify(e));
}

它将只记录{},因为您在Error对象中感兴趣的属性是不可枚举的,而JSON.stringify()只捕获可枚举的属性。

你可以获取你想要的特定属性,将它们作为可枚举属性放入一个新的普通对象中,如下所示:

router.get('/testing', (req, res) => { 
var db = req.db;
var col = db.get('collection'); 
col.find({})
.then((docs) => {res.json(docs);})
.catch((error) => {
const result = {};
result.message = error.message;
result.stack = error.stack;
res.json({errormsg: result});
}); 
});

或者,你可以自己编写一个函数来枚举不可枚举的属性,并将它们复制到一个对象中,作为JSON.stringify()将包含的可枚举属性。

function makeVisibleError(src) {
const result = {};
for (let prop of Object.getOwnPropertyNames(src)) {
result[prop] = src[prop];
}
return result;
}
router.get('/testing', (req, res) => { 
var db = req.db;
var col = db.get('collection'); 
col.find({})
.then((docs) => {res.json(docs);})
.catch((error) => {
const result = makeVisibleError(error);
res.json({errormsg: result});
}); 
});

在真实的应用程序中,您可能不希望将原始错误对象中的所有内容传递回客户端,因此您将手动选择一个或多个属性或制作自己的消息。


供参考,如果您创建自己的Error子类,您可以覆盖toJSON()方法并选择要包含的特定属性。有关更多信息,请参见使Error's message属性可枚举。

最新更新