sumanth.js
sumanth.js

Reputation: 434

how to write custom error message in Postman using nodejs

In my case, if I unselect any field in postman, I got an error in the terminal but I want to print that error message or custom error in the postman response. how to do that?

POST method

  router.post("/admin/add_profile", upload.single("image"), async (req, res) => {
  try {
   const send = new SomeModel({
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    phone: req.body.phone,
    email: req.body.email,
    image: req.file.filename,
  });
   send.save();
   const result = await s3Uploadv2(req.files);
   res.json({ status: "Everything worked as expected", result });
 } catch (err) {
   res.status(404).send(err.message);
 }
});

schema.js

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const SomeModelSchema = new Schema({
  first_name: {
    type: String,
    required: true,
  },
   last_name: {
    type: String,
    required: ["last name is required"],
  },
  phone: {
    type: Number,
    required: ["Phone number is required"],
    unique: true,
    validate: {
      validator: (val) => {
        return val.toString().length >= 10 && val.toString().length <= 12;
      },
    },
  },

  email: {
    type: String,
    trim: true,
    lowercase: true,
    unique: true,
    required: ["email address is required"],
    validate: (email) => {
      return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    },
    match: [
      /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
      "Please fill a valid email address",
    ],
  },

  image: {
    data: Buffer,
    contentType: String 
  }

});

module.exports = mongoose.model("SomeModel", SomeModelSchema);

here I unselected the first_name field but I got an error in the terminal I want to print that error or a custom error in the postman response. postman

error message in terminal terminal

Upvotes: 0

Views: 505

Answers (1)

lpizzinidev
lpizzinidev

Reputation: 13284

You should await the save() call, which returns a Promise.
You should then be able to handle the error in the catch block:

router.post('/admin/add_profile', upload.single('image'), async (req, res) => {
  try {
    const send = new SomeModel({
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      phone: req.body.phone,
      email: req.body.email,
      image: req.file.filename,
    });
    await send.save();
    const result = await s3Uploadv2(req.files);
    res.json({ status: 'Everything worked as expected', result });
  } catch (error) {
    if (error.name === "ValidationError") {
        let errors = [];
        for (const err in error.errors) {
            errors.push(err.message)
        }
        return res.status(400).send(errors);
    }
    res.status(500).send('Server error');
  }
});

Upvotes: 1

Related Questions