Home > Net >  How to pass Mongoose validation errors in Postman response
How to pass Mongoose validation errors in Postman response

Time:10-31

If I enter more than or less than 10 digit number in the phone number field in the postman I get the validation error message in the terminal and the server get crashes but I want to get that error message in postman JSON. how to do that?

schema.js

const { json } = require("body-parser");
const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const SomeModelSchema = new Schema({
phone: {
type: Number,
required:true,
unique: true,
validate: {
  validator: (val) => {
      var re = /^\d{10}$/;
      return (!val ) || re.test(val)
  },
  message: 'Provided phone number is invalid.'
  },
},
module.exports = mongoose.model("SomeModel", SomeModelSchema);

Post method

router.post("/admin/add_profile", async (req, res) => {

try {
  const send = new SomeModel({ 
    phone: req.body.phone,
  });
  send.save();
 
res.json({
    responseMessage: "Everything worked as expected",
  });
} catch (error) {
  res.status(400).send(err.message);
}
});

error message in the terminal but I need to display the error message like phone number is invalid in the postman response enter image description here

CodePudding user response:

You should await your save() call. Otherwise the call continues to run, but it will never reach the catch-block, since the error was thrown asynchronously in your promise.

This is also the reason why your whole app crashes and does not catch this error.

This means that just using await send.save(); should resolve the issue. After that your catch block will be processed. Unfortunately you catch errors in the variable named error, but you try to read the message from the variable named err, which still needs to be corrected.

  • Related