fix: reading error code

Signed-off-by: Muhammad Aaqil <aaqilcs102@gmail.com>
This commit is contained in:
Muhammad Aaqil 2024-04-14 16:49:51 +05:00 committed by Diana Lau
parent 9512f15932
commit de5eac7731
2 changed files with 15 additions and 1 deletions

View File

@ -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)) {

View File

@ -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);
});