Documentation Home
X DevAPI User Guide for MySQL Shell in Python Mode
Download this Manual
PDF (US Ltr) - 1.2Mb
PDF (A4) - 1.2Mb

8.1.2 Error Handling

When writing scripts for MySQL Shell you can often simply rely on the exception handling done by MySQL Shell. For all other languages either proper exception handling is required to catch errors or the traditional error handling pattern needs to be used if the language does not support exceptions.

The default error handling can be changed by creating a custom SessionContext and passing it to the mysqlx.getSession() function. This enables switching from exceptions to result based error checking.

The following example shows how to perform proper error handling. The example assumes that the test schema exists and that the collection my_collection exists.

from mysqlsh import mysqlx


        # Connect to server on localhost
        mySession = mysqlx.get_session( {
                'host': 'localhost', 'port': 33060,
                'user': 'user', 'password': 'password' } )

except Exception as err:
        print('The database session could not be opened: %s' % str(err))

        myDb = mySession.get_schema('test')

        # Use the collection 'my_collection'
        myColl = myDb.get_collection('my_collection')

        # Find a document
        myDoc = myColl.find('name like :param').limit(1).bind('param','L%').execute()

        # Print document
except Exception as err:
        print('The following error occurred: %s' % str(err))
        # Close the session in any case