Skip to content

Instantly share code, notes, and snippets.

@MiguelTVMS
Created April 28, 2017 13:17
Show Gist options
  • Save MiguelTVMS/f81dee5a63d28db4fb8b7e3abd6f4728 to your computer and use it in GitHub Desktop.
Save MiguelTVMS/f81dee5a63d28db4fb8b7e3abd6f4728 to your computer and use it in GitHub Desktop.
Helper function to show mongoose validation errors as bad request (409) on express
function mongooseValidator(err, req, res, next) => {
if (err !== 'undefined' && err.name !== 'undefined' && err.name === 'ValidationError')
return handleValidationError(err, res);
if (err !== 'undefined' && err.code === 11000)
return handleDuplicateValidationError(err, res);
next(err);
}
function handleDuplicateValidationError(err, res) {
res.sendStatus(409);
}
function handleValidationError(err, res) {
var errorMessage = {
message: err.message,
errors: []
};
for (var prop in err.errors) {
errorMessage.errors.push({
propertyName: prop,
propertyPath: err.errors[prop].path,
validation: err.errors[prop].kind,
message: err.errors[prop].message || err.errors[prop].kind
});
}
res.status(400).json(errorMessage);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment