Skip to content

Commit

Permalink
created db error hanler file
Browse files Browse the repository at this point in the history
  • Loading branch information
byohannes committed Sep 24, 2020
1 parent 4fac0ed commit b77b3d5
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions helpers/dbErrorHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"use strict";

/**
* Get unique error field name
*/
const uniqueMessage = (error) => {
let output;
try {
let fieldName = error.message.substring(
error.message.lastIndexOf(".$") + 2,
error.message.lastIndexOf("_1")
);
output =
fieldName.charAt(0).toUpperCase() +
fieldName.slice(1) +
" already exists";
} catch (ex) {
output = "Unique field already exists";
}

return output;
};

/**
* Get the erroror message from error object
*/
exports.errorHandler = (error) => {
let message = "";

if (error.code) {
switch (error.code) {
case 11000:
case 11001:
message = uniqueMessage(error);
break;
default:
message = "Something went wrong";
}
} else {
for (let errorName in error.errorors) {
if (error.errorors[errorName].message)
message = error.errorors[errorName].message;
}
}

return message;
};

0 comments on commit b77b3d5

Please sign in to comment.