From de5eac773127df4e7ea9321e8f0dd2b49ae6f584 Mon Sep 17 00:00:00 2001 From: Muhammad Aaqil Date: Sun, 14 Apr 2024 16:49:51 +0500 Subject: [PATCH] fix: reading error code Signed-off-by: Muhammad Aaqil --- lib/set-http-code.js | 4 +++- test/set-http-code.test.js | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/set-http-code.js b/lib/set-http-code.js index 4196234..ced518d 100644 --- a/lib/set-http-code.js +++ b/lib/set-http-code.js @@ -26,6 +26,8 @@ const codes = { * add your SQL error to the correct HTTP code array above! */ module.exports = function(err) { + let code = ''; + if (err && err.code) code = err.code; if (!err) { return; } else if (!(err instanceof Error)) { @@ -33,7 +35,7 @@ module.exports = function(err) { } // Find error prefix const msg = err.message; - const sqlError = msg.substring(0, msg.indexOf(':')); + const sqlError = msg.substring(0, msg.indexOf(':')) || code; for (const code in codes) { if (_.includes(codes[code], sqlError)) { diff --git a/test/set-http-code.test.js b/test/set-http-code.test.js index e8b0e81..f07a537 100644 --- a/test/set-http-code.test.js +++ b/test/set-http-code.test.js @@ -29,6 +29,18 @@ describe('setHttpCode', function() { }); } }); + + it('should set statusCode from code', function() { + let err = { + message: 'Duplicate entry \'value\' for key \'key_name\'', + code: 'ER_DUP_ENTRY', + }; + err = setHttpCode(err); + should.exist(err.statusCode); + should(err instanceof Error); + should.equal(err.statusCode, 422); + }); + it('should do nothing without error', function() { should.doesNotThrow(setHttpCode); });