8.1.2 錯誤處理

當為 MySQL Shell 編寫腳本時,您通常可以簡單地依賴 MySQL Shell 執行的例外處理。對於所有其他語言,若要捕捉錯誤,則需要適當的例外處理,如果語言不支援例外,則需要使用傳統的錯誤處理模式。

預設錯誤處理可以透過建立自訂的 SessionContext 並將其傳遞給 mysqlx.getSession() 函數來變更。這樣可以從例外切換為基於結果的錯誤檢查。

以下範例示範如何執行適當的錯誤處理。此範例假設測試綱要存在,且集合 my_collection 存在。

var mysqlx = require('mysqlx');

var mySession;

try {
  // Connect to server on localhost
  mySession = mysqlx.getSession( {
    host: 'localhost', port: 33060,
    user: 'user', password: 'password' } );
}
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','L%').execute();

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