在knex事务中引发自定义错误导致api崩溃



我目前正在使用knex开发api。我必须在一个大事务中执行一些操作,并且必须在那里进行赋值——如果任何验证返回"false"——则必须停止事务。问题是,每当我在那里抛出"我的"错误时,即使所有的"Catch"es都得到了它,并且res都被正确发送了——就在那之后,我的整个api都崩溃了,出现了错误:

无法读取空的属性"removeListener">

这很奇怪,因为knex本身没有类似的捕获错误问题。

Strangley,如果我能消除我的错误抛出-我仍然会得到未处理的异常

无法读取空的属性"回滚">

在代码中,它看起来像这样:

f1(){
// (...)
let noErrors = true;
return global.knex
.transaction((trx) => {
return operation1(trx) //Knex operation returning object with parameter "correct"
.then((output)=>{
if(output.correct === false)
throw new Error('CustomError');
})
.then(()=>{ return operation2(trx); })
.then(()=>{ return operation3(trx); })
// (...)
.then(trx.commit)
.catch((error) => {
console.error('TRANS. FAILED');
noErrors = false;
trx.rollback();
throw error; // Both with and without it - failed
});
})
.then(() => {
console.log('TRANS. OK');
})
.then(() => {
if(noErrors)
return {result:'MyResultsHere'};
else
return {result:'ErrorOccured'};
})
.catch((error) => {
return {result:'ErrorOccuredAgain'};
});

}

然后返回此函数的结果(promise):

f1().then((output)=>{ 
console.log(output.result); 
// (...) sending response for request here
}
.catch((err) => {
console.error(err);
res.status(500).send();
});

A经过一些额外的测试-看起来我可以抛出我的自定义错误,但这里的问题是回滚-所以我又得到了一个错误:

TransactionError:请求只能在LoggedIn状态下进行,而不能SentClientRequest状态

看起来您混合了两种不同的事务处理语法(下面的简单示例):

knex.transaction(trx => {
// returning promise automatically calls commit / rollback
return operation(1);
})
.then(results => console.log("commit was called automatically", results))
.catch(err => console.log("rollback was called automatically", err))

knex.transaction(trx => {
// NOT returning promise so you need to call commit / rollback explicitly
operation(1).then(results => trx.commit(results))
.catch(err => trx.rollback(err));
})
.then(results => console.log("stuff from transaction commit", results))
.catch(err => console.log("error passed to rollback", err))

你可能正在尝试这样做:

f1(){
// (...)
return global.knex
.transaction(trx => {
return operation1(trx)
.then(output => {
if(output.correct === false) {
// if wrong results promise will reject with "CustomError"
throw new Error('CustomError');
}
})
.then(() => operation2(trx))
.then(() => operation3(trx))
// (...)
;
})
.then(resultsOfLastThen => {
console.log('TRANS. OK', resultsOfLastOperation);
return { result: 'MyResultsHere' };
})
.catch(error => {
return { result: 'ErrorOccured' };
});
}

最新更新