diff --git a/lib/set-http-code.js b/lib/set-http-code.js index 41962342..ced518d9 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 e8b0e81c..f07a537a 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); });