Skip to content

Commit 829cd5a

Browse files
RUBY-3341 Document error handling in transactions (mongodb#2809)
Co-authored-by: Alex Bevilacqua <[email protected]>
1 parent ba527e1 commit 829cd5a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Diff for: docs/reference/transactions.txt

+33
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,31 @@ which are read concern, write concern and read preference:
7676
collection.insert_one({hello: 'world'}, session: session)
7777
end
7878

79+
Handling Errors Within the ``with_transaction`` Block
80+
-----------------------------------------------------
81+
82+
If a command inside the ``with_transaction`` block fails, it may cause
83+
the transaction on the server to be aborted. This situation is normally handled
84+
transparently by the driver. However, if the application catches such an error
85+
and does not re-raise it, the driver will not be able to determine whether
86+
the transaction was aborted or not. The driver will then retry the block
87+
indefinitely.
88+
89+
To avoid this situation, the application must not silently handle errors within
90+
``with_transaction`` block. If the application needs to handle errors within
91+
the block, it must re-raise the errors.
92+
93+
.. code-block:: ruby
94+
95+
session.with_transaction do
96+
collection.insert_one({hello: 'world'}, session: session)
97+
rescue Mongo::Error::OperationFailure => e
98+
# Do something in response to the error
99+
raise e
100+
end
101+
102+
If the applications needs to handle errors in a custom way, it should use
103+
the low level API instead.
79104

80105
Low Level API
81106
=============
@@ -145,6 +170,14 @@ session if one is in progress:
145170
# ok
146171
c2.database.drop
147172

173+
Handling Errors
174+
---------------
175+
176+
If a command inside the transaction fails, the transaction may be aborted
177+
on the server. Errors that abort transactions do not have
178+
``TransientTransactionError`` in their error labels. An attempt to commit such a
179+
transaction will be rejected with ``NoSuchTransaction`` error.
180+
148181

149182
Retrying Commits
150183
================

0 commit comments

Comments
 (0)