From 42a4edb19c6f54f18128c2be63aa0681698fe9f6 Mon Sep 17 00:00:00 2001 From: Laurent Cozic Date: Tue, 16 Nov 2021 11:31:13 +0000 Subject: [PATCH] Server: Display more detailed error messages on SQL query errors --- packages/server/src/db.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/packages/server/src/db.ts b/packages/server/src/db.ts index ab262fd01a..3d2cab475c 100644 --- a/packages/server/src/db.ts +++ b/packages/server/src/db.ts @@ -185,6 +185,27 @@ export function setupSlowQueryLog(connection: DbConnection, slowQueryLogMinDurat }); } +const filterBindings = (bindings: any[]): Record => { + const output: Record = {}; + + for (let i = 0; i < bindings.length; i++) { + let value = bindings[i]; + if (typeof value === 'string') value = value.substr(0, 200); + if (Buffer.isBuffer(value)) value = ''; + output[`$${i + 1}`] = value; + } + + return output; +}; + +interface KnexQueryErrorResponse { + message: string; +} + +interface KnexQueryErrorData { + bindings: any[]; +} + export async function connectDb(dbConfig: DatabaseConfig): Promise { const connection = knex(makeKnexConfig(dbConfig)); @@ -192,6 +213,13 @@ export async function connectDb(dbConfig: DatabaseConfig): Promise setupSlowQueryLog(connection, dbConfig.slowQueryLogMinDuration); } + connection.on('query-error', (response: KnexQueryErrorResponse, data: KnexQueryErrorData) => { + const msg: string[] = []; + msg.push(response.message); + if (data.bindings && data.bindings.length) msg.push(JSON.stringify(filterBindings(data.bindings), null, ' ')); + logger.error(...msg); + }); + return connection; }