【问题标题】:Error not being thrown inside async function未在异步函数中引发错误
【发布时间】:2019-07-02 14:19:41
【问题描述】:

我有一个将一些数据插入数据库的异步函数(使用mariadb)。由于重复的唯一键,此插入可能会失败,因此它会抛出错误(实际上确实如此),但是当我尝试再次抛出它以通过 Promise 捕获它时,它不起作用;它似乎总是以成功的情况结束,即使它抛出了错误。

我尝试更改 then/catch 顺序,并使用 reject(err); 而不是 throw err;,但这些都不起作用。

这是 POST 声明:

router.post('/', function (req, res) {
    var user = req.body || {};
    createUser(user).then(() => {
        res.status(201); 
        res.send('Created!'); // This is ALWAYS sent, with the error thrown or not
    }).catch(err => {
        console.log('thrown'); // This is never printed
        res.status(500);
        res.send('Failed');
    });
});

这是创建用户功能:

async function createUser(user) {
    let conn;
    try {
        conn = await db.getConnection();
        const res = await conn.query('INSERT INTO users VALUES (NULL, ?, ?)', [user.name, user.password]); // Shorter example
        return res;
    } catch (err) {
        console.log('catched'); // This is printed
        throw err; // This is run but nothing thrown
    } finally {
        if (conn) {
            return conn.end(); // This is run after catching
        }
    }
} 

我们的想法是让 Promise 捕获该异常,这样我就可以发送错误消息而不是成功消息。

【问题讨论】:

    标签: javascript node.js express asynchronous


    【解决方案1】:

    问题在于finally 中的 return 语句。在async 函数中,如果您捕获它抛出异常,则抛出finally 并返回一些东西,而不是抛出它,而是将承诺解析为您的返回值。据我所知,您不需要结束连接的对象作为返回值,这意味着您所要做的就是将您的函数更改为:

    async function createUser(user) {
        let conn;
        try {
            conn = await db.getConnection();
            const res = await conn.query('INSERT INTO users VALUES (NULL, ?, ?)', [user.name, user.password]); // Shorter example
            return res;
        } catch (err) {
            console.log('catched'); // This is printed
            throw err; // This is run but nothing thrown
        } finally {
            if (conn) {
                conn.end(); // This is run after catching
            }
        }
    }
    

    【讨论】:

    • 谢谢!我没有意识到 return 语句甚至在那里,它可能是一个复制粘贴错误。正如你所说,如果先返回某些东西,承诺会在捕获之前解决。
    猜你喜欢
    • 2020-04-02
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多