gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:00:24 27 4
gpt4 key购买 nike

在查找当时可能不存在的特定文档时,如何防止 ArangoDB 在事务期间抛出异常?

Nodejs 将一个区块中的交易发送到 ArangoDb,在那里进行处理。那很完美。我想将所有数学卸载到服务器。

在交易期间,我想查看特定的集合并检查文档是否存在,如果可以找到文档,则获取字段“余额”,但是如果找不到文档或其字段,那么我不想抛出异常并且不想停止正在进行的事务。相反,我更想继续交易,我们为变量 oldBalance 分配了字符串“0”。

(供您引用:集合有一个写锁:在 nodeJS 端指定的“用户”)
在这里您可以看到发送到 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;
}

最佳答案

你不能像这样处理事务中的“文档未找到”错误:

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

关于transactions - ArangoDB 事务 - 如何防止抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23934058/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com