Skip to content

Commit fd4a17a

Browse files
MongoCalebmmarcon
andauthored
add section explaining the use of the exit() method (#314)
* add section explaining the use of the exit() method * Update source/write-scripts.txt Co-authored-by: Massimiliano Marcon <[email protected]> --------- Co-authored-by: Massimiliano Marcon <[email protected]>
1 parent 96b8cf2 commit fd4a17a

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

source/run-commands.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,11 @@ it issues a warning.
104104
Pressing ``Ctrl + C`` once will not exit :binary:`~bin.mongosh`, press
105105
``Ctrl + C`` twice to exit :binary:`~bin.mongosh`.
106106

107+
You can also terminate a script from within the script code by calling the
108+
``exit(<code>)`` command. For more information, refer to
109+
:ref:`Terminate a Script on Error <mongosh-terminate-script>`.
110+
111+
107112
Command Exceptions
108113
------------------
109114

source/write-scripts.txt

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,24 @@ You can also specify the shortened form of the options:
271271
space it will not be saved in your command history. This minimizes
272272
exposure if you enter passwords on the command line.
273273

274+
275+
.. _mongosh-terminate-script:
276+
277+
Terminate a Script on Error
278+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
279+
280+
It is often useful to terminate a running script if an exception is thrown, or
281+
in the case of unexpected results. Exiting at a specific point in the script
282+
prevents the execution of unnecessary code and potentially unexpected results.
283+
284+
To terminate a script, you can call the ``exit(<code>)`` method, where the
285+
``<code>`` is any user-specified value.
286+
287+
As a best practice, wrap code in a ``try - catch``, calling the
288+
``exit`` method in the ``catch`` block. Likewise, to check the results of a query or any command,
289+
you can add an ``if - else`` statement and call the ``exit`` method if the
290+
results are not what is expected.
291+
274292
.. _mongosh-write-scripts-config-file:
275293

276294
Execute Code From a Configuration File

0 commit comments

Comments
 (0)