ArangoDB事务 - 如何防止抛出异常

4
如何防止ArangoDB在事务期间查找特定文档时引发异常,即使该文档此时可能不存在?
Nodejs将事务作为一个块发送到ArangoDb中进行处理。这很完美,我想将所有数学计算都卸载到服务器上。
在事务期间,我想查看特定集合并检查是否存在文档。如果可以找到文档,则获取字段“balance”,但如果找不到文档或它们的字段,则我不想抛出异常或停止正在进行的事务。相反,我更希望继续进行事务,并将变量oldBalance分配为字符串“0”。
(供您参考:在nodeJS端指定了集合“user”的写锁)以下是发送到ArangoDB的事务代码的一部分:
var db = require('internal').db;
// 1.) find specific document
var accountdoc = db.user.document('Johnny04'); // find doc by _key

如果找不到具有特定_key的那个文档,这将抛出异常。此时,用户可能在集合中没有条目。在这种情况下,我们希望假定他的余额为字符串“0”。但不幸的是,异常已经被抛出。我更希望按照以下方式继续:

//2.) calculate newBalance = oldBalance + additional
        if (accountdoc.error==true){ // document not found etc...
            var oldBalance='0';
            var documentExists = false;
        } else {
            var oldBalance=accountdoc.balance;
            var documentExists = true;
            var documentExistsID = accountdoc._id;
        }   
1个回答

4
你不能像这样在事务中处理“文档未找到”错误吗:
function (params) {
  var db = require("org/arangodb").db;
  var accountdoc;

  // 1.) find specific document
  try {
    accountdoc = db.user.document('Johnny04'); // find doc by _key
  }
  catch (err) {
    // document not found etc.
    // TODO: rethrow exception if err is something different than "document not found"
  }

  // 2.) calculate newBalance = oldBalance + additional
  if (accountdoc === undefined) { // document not found etc...
    // create a new document with balance 0
    db.user.save({ _key: 'Johnny04', balance: '0' }); // note: if this fails, the transaction will throw
  } 
  else {
    // update the existing document
    var oldBalance = accountdoc.balance;
    var newBalance = oldBalance + 42;
    db.user.update('Johnny04', { balance: newBalance }); // note: if this fails, the transaction will throw
  }   
}

1
哇,那个完美地运行了。感谢你的 try 和 catch 块,它起到了作用。 - europeanguy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接