Application Development with MariaDB Connector/Node.js (Promise API)

MariaDB Connector/Node.js database applications can be installed using NPM. Developers should also consider strategies for exception handling to manage any errors raised from the database layer.

Install Application

To install your database application, use NPM:

$ npm install

Exception Handling

MariaDB Connector/Node.js Promise API supports exception handling by returning or throwing the Error object. When the MariaDB Connector/Node.js encounters an error condition, a Promise rejects with an Error object. Exception handling as a built-in feature is discussed for the three commonly used methods:



Exception Handling


Runs a single SQL statement.

Returns a Promise that rejects with an Error object.


Runs a batch of SQL statements.

Returns a Promise that rejects with an Error object.


Runs an SQL query, using different functions for the return values.

Sends an Error object when the query fails.

The trace Option

The default exception stack trace output is a limited/summarized list. To list the initial stack trace in the Error object error message for debugging, set the trace connection option to true as follows:

conn = await mariadb.createConnection({
         user: "db_user",
         host: "",
         password: "db_user_password",
         database: "test",
         trace: true

The try...catch...finally Statement

The Error object returned by a Promise, or sent otherwise, can be handled with a JavaScript try-catch-finally statement. The MariaDB Connector/Node.js code should be run in the try block. The catch block catches the Error object if any and logs a message indicating an error condition. The optional finally block can be used to run other code such as close open resources including SQL statements, prepared statements, result sets, and connections. An example of using the try...catch...finally statement is follows:

try {
       //Create a Connection using the MariaDB Connector/Node.js
      // conn =  ...

       // Use Connection
        // ...
       // Catch error

     } catch (err) {
       // Manage Errors
       console.log("SQL error : ", err);

     } finally {

       // Close SQL resources
       if (conn) conn.close();

The catch() method

The Promise API also provides the catch() method, which returns a Promise object, to handle an error condition. The catch() method could be used at the end of a sequence of function calls that each return a Promise object as follows:

const conn= await mariadb.createConnection({...});
                        then(()=>conn.query("INSERT INTO testTable.... )).
                        then(()=> {conn.commit();}).
                        catch(err=> {conn.rollback()});