【问题标题】:Async - Await JavaScript: unable to catch error details from an Error object [duplicate]异步 - 等待 JavaScript:无法从错误对象中捕获错误详细信息 [重复]
【发布时间】:2021-08-25 23:17:22
【问题描述】:

在我的 Node Express JS Web 应用程序中,我有以下函数链,其中后续 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 一直是空的。

【问题讨论】:

  • 尝试显示err.stack 显示的内容?

标签: javascript node.js express async-await try-catch


【解决方案1】:

未指定错误属性的精确位置。在某些环境中,它位于错误对象本身上 - 在某些环境中,它位于原型上,或者是一个 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 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-20
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    • 2011-01-31
    • 2017-11-09
    • 2019-02-11
    相关资源
    最近更新 更多