changeset 747:56d48f6e52cc

catching exceptions in python plugins
author Sebastien Jodogne <s.jodogne@gmail.com>
date Mon, 09 Aug 2021 18:29:38 +0200
parents b2b1ba11faaa
children a296fe06fd86
files Sphinx/source/plugins/python.rst Sphinx/source/plugins/python/exception.py
diffstat 2 files changed, 36 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/Sphinx/source/plugins/python.rst	Sat Aug 07 10:40:52 2021 +0200
+++ b/Sphinx/source/plugins/python.rst	Mon Aug 09 18:29:38 2021 +0200
@@ -695,7 +695,25 @@
 embedded DICOM dataset into Orthanc. Obviously, one can build more
 complex DICOM servers by handling more messages than C-STORE alone.
 
-  
+
+.. _python_exception:
+
+Catching exceptions
+...................
+
+Starting with release 3.3 of the Python plugin, the plugin generates a
+Python exception derived from class ``orthanc.OrthancException`` if an
+error is encountered. This exception contains a tuple that provides
+the error code and its textual description.
+
+In releases <= 3.2, the Python plugin raised the `built-in exception
+<https://docs.python.org/3/library/exceptions.html>`__ ``ValueError``.
+
+Here is an example showing how to catch exceptions:
+
+.. literalinclude:: python/exception.py
+                    :language: python
+
 
 Performance and concurrency
 ---------------------------
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Sphinx/source/plugins/python/exception.py	Mon Aug 09 18:29:38 2021 +0200
@@ -0,0 +1,17 @@
+import orthanc
+
+def OnChange(changeType, level, resource):
+    if changeType == orthanc.ChangeType.ORTHANC_STARTED:
+        try:
+            print(orthanc.RestApiGet('/nope'))
+        except ValueError as e:
+            # Raised in releases <= 3.2 of the plugin (doesn't occur in releases >= 3.3)
+            print(e)
+        except orthanc.OrthancException as e:
+            # Raised in releases >= 3.3 of the plugin (fails with releases <= 3.2)
+            print(e)
+            print(e.args[0])  # Error code of Orthanc (cf. "orthanc.ErrorCode" enumeration)
+            print(e.args[1])  # Description of the error
+            print(e.args[0] == orthanc.ErrorCode.UNKNOWN_RESOURCE)  # Returns "True"
+
+orthanc.RegisterOnChangeCallback(OnChange)