[Fixed] How to customize Mongoose/MongoDB error sent from Express

Issue

I am sending an error message back to my iOS client when a user tries to create a password that contains the word ‘password’.

I want to display a simple message to the user without having to slice strings, etc on the client so I DO NOT want to send the part ‘User validation failed: password:‘ ONLY ‘password cannot contain the word password‘.

How do I customize this message in Node/Express? Is it a Mongoose or MongoDB implementation?

Thank you!

// Mongoose password model.
password : {
     type: String,
     required: [true, "password is required"],
     validate(value) {
         if (value.length < 6) {
             throw new Error(`password must be longer than 6 characters`)
            }
         if (value.toLowerCase().includes(`password`)) {
             throw new Error(`password cannot contain the word ${value}`)
            }
        },
     trim: true,
     minLength: [6, "password cannot be shorter than 8 characters"],
     maxlength: [80, "name cannot be longer than 30 characters"]
    },

// Router error response
catch(err) {
        console.log(err.message)     
        res.status(500).send({error: err.message}) 
    }
-> User validation failed: password: password cannot contain the word password

Solution

You can always customize error messages before sending them in Express:

catch(err) {
  console.log(err.message) 
  // Add Message Customization Here:
  const message = err.message.replace("User validation failed: password:", "");    
  res.status(500).send({error: message}) 
}

Leave a Reply

(*) Required, Your email will not be published