Skip to content

Commit

Permalink
fix: reading error code
Browse files Browse the repository at this point in the history
Signed-off-by: Muhammad Aaqil <[email protected]>
  • Loading branch information
aaqilniz authored and dhmlau committed Apr 17, 2024
1 parent 9512f15 commit de5eac7
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/set-http-code.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,16 @@ 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)) {
err = new Error(err); // Sucks that we weren't given an error object...
}
// 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)) {
Expand Down
12 changes: 12 additions & 0 deletions test/set-http-code.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down

0 comments on commit de5eac7

Please sign in to comment.