提问者:小点点

异步函数中未引发错误


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

我尝试改变then/catch顺序,我使用了< code > reject(err);而不是< code >抛出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个答案

匿名用户

问题在于您的最后中的返回语句。在抛出异常后的async函数中,如果您抓住它,则抛出最后并返回一些东西,而不是抛出它将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
        }
    }
}