Documentation Home
X DevAPI User Guide
Download this Manual
PDF (US Ltr) - 1.0Mb
PDF (A4) - 1.0Mb
EPUB - 0.7Mb
HTML Download (TGZ) - 0.6Mb
HTML Download (Zip) - 0.7Mb


X DevAPI User Guide  /  Statement Execution  /  Error Handling

Pre-General Availability Draft: 2017-04-28

8.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 examples show how to perform proper error handling for the various languages. The example assumes that the test schema exists and that the collection my_collection exists.

MySQL Shell JavaScript Code

var mysqlx = require('mysqlx');

var mySession;

try {
  // Connect to server on localhost
  mySession = mysqlx.getNodeSession( {
    host: 'localhost', port: 33060,
    dbUser: 'mike', dbPassword: 's3cr3t!' } );
}
catch (err) {
  print('The database session could not be opened: ' + err.message);
}

try {
  var myDb = mySession.getSchema('test');

  // Use the collection 'my_collection'
  var myColl = myDb.getCollection('my_collection');

  // Find a document
  var myDoc = myColl.find('name like :param').limit(1)
    .bind('param','S%').execute();

  // Print document
  print(myDoc.first());
}
catch (err) {
  print('The following error occurred: ' + err.message);
}
finally {
  // Close the session in any case
  mySession.close();
}
    

MySQL Shell Python Code

import mysqlx

# Connect to server
mySession = mysqlx.get_node_session( {
        'host': 'localhost', 'port': 33060,
        'dbUser': 'mike', 'dbPassword': 's3cr3t!' } )

# Get the Schema test
myDb = mySession.get_schema('test')

# Create a new collection
myColl = myDb.create_collection('my_collection')

# Start a transaction
mySession.start_transaction()
try:
    myColl.add({'name': 'Jack', 'age': 15, 'height': 1.76, 'weight': 69.4}).execute()
    myColl.add({'name': 'Susanne', 'age': 24, 'height': 1.65}).execute()
    myColl.add({'name': 'Mike', 'age': 39, 'height': 1.9, 'weight': 74.3}).execute()
    
    # Commit the transaction if everything went well
    reply = mySession.commit()
    
    # handle warnings
    if reply.warning_count:
      for warning in result.get_warnings():
        print 'Type [%s] (Code %s): %s\n' % (warning.level, warning.code, warning.message)
    
    print 'Data inserted successfully.'
except Exception, err:
    # Rollback the transaction in case of an error
    reply = mySession.rollback()
    
    # handle warnings
    if reply.warning_count:
      for warning in result.get_warnings():
        print 'Type [%s] (Code %s): %s\n' % (warning.level, warning.code, warning.message)
    
    # Printing the error message
    print 'Data could not be inserted: %s' % str(err)
    

Node.js JavaScript Code

var mysqlx = require('mysqlx');

// Connect to server on localhost
mysqlx.getSession( {
    host: 'localhost', port: 33060,
    dbUser: 'mike', dbPassword: 's3cr3t!'
}).then(function (mySession) {
  // This can't throw an error as we check existence at a later operation only
  var myDb = mySession.getSchema('test');

  // Use the collection 'my_collection'
  // This can't throw an error as we check existence at a later operation only
  var myColl = myDb.getCollection('my_collection');

  // Find a document
  myColl.find('name like :param').limit(1)
  .bind('param','S%').execute(function (row) {
    console.log(row);
  }).catch(function (err) {
    print('The following error occurred: ' + err.message);
  });

  session.close();
}).catch (err) {
  console.log('The database session could not be opened: ' + err.message);
});

C# Code


Java Code

import com.mysql.cj.api.xdevapi.*;
import com.mysql.cj.xdevapi.*;

XSession mySession;

try {
    // Connect to server on localhost
    mySession = new XSessionFactory().getSession("mysqlx://localhost:33060/test?user=mike&password=s3cr3t!");

    try {
        Schema myDb = mySession.getSchema("test");

        // Use the collection 'my_collection'
        Collection myColl = myDb.getCollection("my_collection");

        // Find a document
        DocResult myDoc = myColl.find("name like :param").limit(1).bind("param", "S%").execute();

        // Print document
        System.out.println(myDoc.fetchOne());
    } catch (XDevAPIError err) { // special exception class for server errors
        System.err.println("The following error occurred: " + err.getMessage());
    } finally {
        // Close the session in any case
        mySession.close();
    }
} catch (Exception err) {
    System.err.println("The database session could not be opened: " + err.getMessage());
} 

C++ Code

#include <mysqlx.h>

try
{
  // Connect to server on localhost
  XSession session(33060, "mike", "s3cr3t!");

  try
  {
    Schema db = session.getSchema("test");

    // Use the collection 'my_collection'
    Collection myColl = db.getCollection("my_collection");

    // Find a document
    auto myDoc = myColl.find("name like :param").limit(1)
                       .bind("param", "S%").execute();

    // Print document
    cout << myDoc.fetchOne() << endl;

    // Exit with success code
    exit(0);
  }
  catch (const Error &err)
  {
    cout << "The following error occurred: " << err << endl;
    exit(1);
  }

  // Note: session is closed automatically when session object
  // is destructed.
}
catch (const Error &err)
{
  cout << "The database session could not be opened: " << err << endl;

  // Exit with error code
  exit(1);
}

User Comments
Sign Up Login You must be logged in to post a comment.