From e34016667fc8fdc795b74fc9474e011e4186be44 Mon Sep 17 00:00:00 2001 From: matt Date: Mon, 21 Mar 2022 09:12:48 +0000 Subject: [PATCH] Catch database errors and prevent them from crashing the app --- lib/DatabaseConnectionPool.js | 19 ++++++++++++++----- lib/PasswordReset.js | 11 +++++++---- lib/TestTemplate.js | 14 ++++++++++++-- lib/User.js | 2 ++ 4 files changed, 35 insertions(+), 11 deletions(-) diff --git a/lib/DatabaseConnectionPool.js b/lib/DatabaseConnectionPool.js index 4878743..3e71432 100644 --- a/lib/DatabaseConnectionPool.js +++ b/lib/DatabaseConnectionPool.js @@ -98,11 +98,20 @@ class DatabaseConnectionPool { const prepared = sql.includes('?'); let data; - if (!prepared) { - [ data ] = await this.#connectionPool.execute(sql); - } else { - [ data ] = - await this.#connectionPool.execute(sql, params); + try { + if (!prepared) { + [ data ] = await this.#connectionPool.execute( + sql + ); + } else { + [ data ] = await this.#connectionPool.execute( + sql, + params + ); + } + } catch (e) { + console.error(e); + data = []; } return data; diff --git a/lib/PasswordReset.js b/lib/PasswordReset.js index 8b16bec..67b6304 100644 --- a/lib/PasswordReset.js +++ b/lib/PasswordReset.js @@ -72,9 +72,7 @@ class PasswordReset { where userId = ?; `; - await conn.runQuery(sql, [ u.id ]); - - conn.close(); + let result = await conn.runQuery(sql, [ u.id ]); const [ nonce, token ] = await PasswordReset.hashToken(u); @@ -93,13 +91,18 @@ class PasswordReset { values (?, ?, ?, FROM_UNIXTIME(?)); `; - await conn.runQuery(sql, [ + result = await conn.runQuery(sql, [ u.id, token, nonce, expires ]); + if (!result) + throw new Error('Could not create password reset'); + + conn.close(); + return new PasswordReset(u.id, token); } } diff --git a/lib/TestTemplate.js b/lib/TestTemplate.js index 19dd96a..073821f 100644 --- a/lib/TestTemplate.js +++ b/lib/TestTemplate.js @@ -99,13 +99,18 @@ class TestTemplate { const conn = await new DatabaseConnectionPool(); - await conn.runQuery(sql, [ + const result = await conn.runQuery(sql, [ id, this.id, c.id, epochDate ]); + conn.close(); + + if (!result.length) + throw new Error('Could not assign class'); + return new Test(id); } @@ -130,13 +135,18 @@ class TestTemplate { (?, ?, ?, ?); `; - await conn.runQuery(sql, [ + const result = await conn.runQuery(sql, [ id, a.id, name, maxMark ]); + conn.close(); + + if (!result) + throw new Error('Could not create test template'); + return new TestTemplate(id); } } diff --git a/lib/User.js b/lib/User.js index 311f8d4..a587803 100644 --- a/lib/User.js +++ b/lib/User.js @@ -94,6 +94,8 @@ class User { return new (require(`./${className}`))(this.id); } + + throw new Error('No user found'); })(); }