I am a newbie in the node.js environment. I used to code dotNet and I am trying to get used to node.js.
Projects that I made in MVC .net, I was using middleware for exception handler and if a validation error occurs I was throwing CustomException which has a property describes the error is validation error or not.
I am trying to do this strategy in express.js. I use express-validator
router.post("/register", validators, (req, res) => {
validationResult(req).throw();
var userDto = req.dto;
userService.registerUser(userDto)
.then(result => {
res.status(200).send("User Created Succesfully");
}).
catch(err => {
//log it,
res.status(500).send("");
})
})
if error occurs experss-validator throws an error with 'Validation failed' message
global error handler like
app.use((err,req,res,nex)=>{
if(err.message ==='Validation failed'){
console.log(err);
res.status(422).send(err.array());
}
console.log(err);
});
As you see in the error handler, I tried to understand if the error is validation error or not by control the error message. It seems ugly, isn't it?
In general, I have not seen this approach in node.js. Could it be the abstraction of single responsibility or something else? It seems node.js tries to keep simple Error stuff. I am suffering that lack of this mechanism. Maybe I am doing anti-pattern but I could not figure it out. If you have a better approach I will immediately give up mine :)
Thanks.
express-validatorfor that though)