错误未在异步函数内引发

时间:2019-07-02 14:19:41

标签: javascript node.js express asynchronous

我有一个异步函数,该函数将一些数据插入数据库(使用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捕获该异常,以便我发送错误消息而不是成功消息。

1 个答案:

答案 0 :(得分:2)

问题出在finally内的return语句。如果引发异常,则在async函数中引发异常后,抛出finally并返回一些内容,而不是引发异常,而是将promise解析为返回值。从我看来,您不需要终止连接的对象作为返回值,这意味着您要做的就是将函数更改为此:

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
        }
    }
}