异步 - 等待 JavaScript:无法从错误对象捕获错误详细信息
Async - Await JavaScript: unable to catch error details from an Error object
在我的 Node Express JS 网络应用程序中,我有以下函数链,其中后续 api 函数尝试调用服务函数并捕获从服务函数抛出的错误。
在FWBDataExtracService.js
const FWBDataExtracService = {
getFWBData: async () => {
... ...
// Check if .tabledata exists; If not, throw an error to be caught in the calling function.
if ($('.tabledata1').length == 0) {
console.error("DOM element .tabledata not found on the page.");
throw new Error("DOM element .tabledata not found on the page.");
}
... ...
}
}
在 api.js
中,路由器函数正在尝试调用 FWBDataExtracService.getFWBData 函数,然后捕获错误。
const FWBDataExtracService = require('../services/FWBDataExtracService')
router.get('/GetDataFromFWB', async (req, res, next) => {
try {
.... ....
// ### THIS WILL FAIL AND AN ERROR WILL BE THROWN
const FWBJson = await FWBDataExtracService.getFWBData();
.... ....
} catch(err) {
// ### ERR IS ALWAYS EMPTY
console.log("*", JSON.stringify(err));
return res.send({'Error': JSON.stringify(err)});
}
})
由于错误被模仿,我期待错误被捕获并打印出错误消息。但是 err
总是空的。
未指定错误属性的准确位置。在某些环境中,它在错误对象本身上 - 在某些环境中,它在原型上,或者是 getter,或类似的东西。
JSON.stringify
只会迭代可枚举的自身属性。在Chrome中,.message
属性是不可枚举的,所以字符串化时不会包含:
const e = new Error('foo');
console.log(Object.getOwnPropertyDescriptor(e, 'message'));
此处最好的方法是显式提取所需的属性,而不是使用 JSON.stringify
。变化
console.log("*", JSON.stringify(err));
类似
const { message } = err;
console.log("*", message);
return res.send({ Error: message });
在我的 Node Express JS 网络应用程序中,我有以下函数链,其中后续 api 函数尝试调用服务函数并捕获从服务函数抛出的错误。
在FWBDataExtracService.js
const FWBDataExtracService = {
getFWBData: async () => {
... ...
// Check if .tabledata exists; If not, throw an error to be caught in the calling function.
if ($('.tabledata1').length == 0) {
console.error("DOM element .tabledata not found on the page.");
throw new Error("DOM element .tabledata not found on the page.");
}
... ...
}
}
在 api.js
中,路由器函数正在尝试调用 FWBDataExtracService.getFWBData 函数,然后捕获错误。
const FWBDataExtracService = require('../services/FWBDataExtracService')
router.get('/GetDataFromFWB', async (req, res, next) => {
try {
.... ....
// ### THIS WILL FAIL AND AN ERROR WILL BE THROWN
const FWBJson = await FWBDataExtracService.getFWBData();
.... ....
} catch(err) {
// ### ERR IS ALWAYS EMPTY
console.log("*", JSON.stringify(err));
return res.send({'Error': JSON.stringify(err)});
}
})
由于错误被模仿,我期待错误被捕获并打印出错误消息。但是 err
总是空的。
未指定错误属性的准确位置。在某些环境中,它在错误对象本身上 - 在某些环境中,它在原型上,或者是 getter,或类似的东西。
JSON.stringify
只会迭代可枚举的自身属性。在Chrome中,.message
属性是不可枚举的,所以字符串化时不会包含:
const e = new Error('foo');
console.log(Object.getOwnPropertyDescriptor(e, 'message'));
此处最好的方法是显式提取所需的属性,而不是使用 JSON.stringify
。变化
console.log("*", JSON.stringify(err));
类似
const { message } = err;
console.log("*", message);
return res.send({ Error: message });