From 91b47111035e3af270bda77859fff82ccb774a12 Mon Sep 17 00:00:00 2001 From: Mhykol Date: Wed, 8 May 2024 04:02:36 -0400 Subject: Improve error handling and logging in database module --- scripts/shop.js | 18 ++++++++++++------ source/database.js | 22 +++++++++++++++++++--- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/scripts/shop.js b/scripts/shop.js index 87ddc0c..e75d289 100644 --- a/scripts/shop.js +++ b/scripts/shop.js @@ -18,12 +18,18 @@ class Shop { ` } - for (let i = 0; i < output[0].length; i++) { - data.body += ` -
-

${output[0][i].ProductName}

-

ID: ${output[0][i].ID}

-
+ if (output) { + for (let i = 0; i < output[0].length; i++) { + data.body += ` +
+

${output[0][i].ProductName}

+

ID: ${output[0][i].ID}

+
+ ` + } + } else { + data.body = ` + There are no items in the database. ` } return data.start + data.body + data.end diff --git a/source/database.js b/source/database.js index 78e8a1f..84fc6c7 100644 --- a/source/database.js +++ b/source/database.js @@ -5,15 +5,31 @@ require('dotenv').config() // Authenticates with SQL server and send query class Database { constructor(x) { - this.pool = mysql.createPool({ + this.pool = this.#CreatePool(x) + this.pool.on('acquire', (connection) => {logger.Info('Connection acquired from pool')}) + } + + async Query(x) { + try { + return await this.pool.query(x) + } catch (err) { + if (err.code === 'ECONNREFUSED') { + logger.Error(`Database connection failed: ${err.message}`) + } else { + logger.Error(`Failed to query database: ${err.message}`) + } + return null + } + } + + #CreatePool(x) { + return mysql.createPool({ host: process.env.MYSQL_HOST, user: process.env.MYSQL_USER, password: process.env.MYSQL_PASSWORD, database: x }).promise() } - - async Query(x) {try {return await this.pool.query(x)} catch (err) {logger.Error(err)}} } module.exports = (x) => {return new Database(x)} -- cgit v1.2.3-70-g09d2