Created
April 28, 2017 13:17
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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