Application Development with MariaDB Connector/Node.js (Promise API)
This page is part of MariaDB's Documentation.
The parent of this page is: MariaDB Connector/Node.js with Promise API
Topics on this page:
Overview
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:
Function | Description | Exception Handling |
|---|---|---|
| Runs a single SQL statement. | Returns a |
| Runs a batch of SQL statements. | Returns a |
| Runs an SQL query, using different functions for the return values. | Sends an |
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({
host: "192.0.2.50",
user: "db_user",
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 (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({...});
conn.beginTransaction().
then(()=>conn.query("INSERT INTO testTable.... )).
then(()=> {conn.commit();}).
catch(err=> {conn.rollback()});
