Reputation: 2315
i'm trying to figure out with transactions (i'm using neo4j 1.8.2), but can't really understand how do i handle errors.
For example i'm creating node:
public Node createNode() {
Transaction tx = getGraphDb().beginTx();
try {
Node node = graphDb.createNode();
tx.success();
return node;
} finally {
tx.finish();
}
}
What happens if node is not created and how do i get it? Should i check if node is null?
Upvotes: 0
Views: 1452
Reputation: 5001
You could use the following code snippet. The exception in the catch clause will tell you what went wrong.
Transaction tx = graphDb.beginTx();
Node n = null;
try {
n = graphDb.createNode();
tx.success();
} catch (Exception e) {
tx.failure();
} finally {
tx.finish();
}
The transaction will be rolled back on tx.finish()
when tx.failure()
is called.
NOTICE: org.neo4j.graphdb.Transaction.finish() has been deprecated in favour of try-with-resource statements see: http://javadox.com/org.neo4j/neo4j-kernel/2.0.3/deprecated-list.html.
Now proper way would be:
try ( Transaction tx = graphDatabaseService.beginTx() )
{
//work here
tx.success();
}
Upvotes: 2
Reputation: 3054
tx.failure() isn't really needed in this case. The absence of tx.success() will roll back the transaction as well. So you can say that it's exception-controlled transaction management.
Upvotes: 1