User validation failed: email: Invalid Email, Custom Error Needed - node.js

I am using validator npm package to validate if email is correct.
All that i need is to send a custom message - Invalid Email
but I am getting this -
User validation failed: email: Invalid Email
const UserSchema = mongoose.Schema({
email:{
type: String,
unique: true,
required: true,
trim: true,
lowercase: true,
validate: [isEmail, 'Invalid Email']
},
});
All is good but when i am catching that error and logging it -
user.save().then(data => {
res.status(201).send(data);
}).catch(err => {
console.log(err.message); // this line here logs out the error message
return res.status(500).send({
message: err.message
});
})
I need this - Invalid Error instead of User validation failed: email: Invalid Email
Thanks in advance!

You have 2 solutions here:
1. Edit the validator package and remove the 'User validation failed' line totally.
2. Split the error message:
var errMessageArray = err.message.split(':');
var messageToReturn = errMessageArray[errMessageArray.length - 1]

Related

How to implement Joi validation in hapi.js?

I just want to implement Joi in Hapi API.
server.route([
{
method: 'POST',
path: '/login',
config: {
tags: ['login', 'auth'],
auth: false,
validate: {
payload: payloadValidator,
failAction: (req, h, source, error) => {
console.log("Error ::: ", source.details[0].message);
return h.response({ code: 0, message: source.details[0].message });
}
}
},
handler: async (request, h) => {
console.log(request.payload.email);
console.log(request.payload.password);
...
}
}
]);
Hear I call payloadValidator.
const payloadValidator = Joi.object({
email: Joi.string().required(),
password: Joi.string().required()
}).options({ allowUnknown: true });
Actually I'm new with hapi and I'm missing something in my code. Can anyone help me to fix this issue?
Required output
If I do not pass email then the app must throw an error of Email is required and it should be the same with the password field also.
Error:
Error ::: "email" is required
Debug: internal, implementation, error
Error: Lifecycle methods called before the handler can only return an error, a takeover response, or a continue signal
at Request._lifecycle (/var/www/html/hapi/node_modules/#hapi/hapi/lib/request.js:326:33)
at process._tickCallback (internal/process/next_tick.js:68:7)
As an error suggests Lifecycle methods called before the handler can only return an error, a takeover response, or a continue signal you have to return takeover response.
return h.response({ code: 0, message: source.details[0].message }).takeover();
For more information you can visit this link : reference link

Display specific error message of Validation Error message with node js

How to display a specific error message from a Validation Error. I already display the error with this line of code return res.render("register", {error: err.message});
and show this error ValidationError: User validation failed: email: Email already exists
But it is showing my column field name 'email' and I don't wanna do that. Below is the whole error and I only want to display this message: 'Email already exists'
Ignore the location D: i removed my file directory
ValidationError: User validation failed: email: Email already exists
at ValidationError.inspect
errors:
{ email:
{ ValidatorError: Email already exists
at new ValidatorError (D:)
at validate (D:)
at D:
at process._tickCallback (internal/process/next_tick.js:68:7)
message: 'Email already exists',
name: 'ValidatorError',
properties: [Object],
kind: 'user defined',
path: 'email',
value: 'email#gmail.com',
reason: undefined,
[Symbol(mongoose:validatorError)]: true } },
_message: 'User validation failed',
name: 'ValidationError' }
To get a specific error message of Validation Error you can use mapped() function like below.
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors.mapped().email.msg);
}
To access nested error message do this
err.errors.email.message
Simply create one temp variable and structure your message,
let err_msg = err.errors.email.message;
which will give: 'Email already exists'
You can leave user validation failed message, since same message may be repeated for all validations.

adCreative create Error: 'Invalid parameter' code: 1487390

Cannot create adCreative. Get an error:
Adcreative Create Failed: The Adcreative Create Failed for the following reason: Oops, something went wrong. Please try again later
and in the same error stack:
message: 'Invalid parameter'
code: 1487390
My code:
exports.create = (data, campaign) => {
return new adsSdk.AdCreative({
body: data.appearance.vacancyDescription,
image_url: data.appearance.backgroundImage,
name: `Creative for campaign ${campaign.id}`,
link_url: data.appearance.link,
title: data.appearance.linkDescription,
object_story_spec: {
instagram_actor_id: 'xxxxxx',
page_id: 'xxxxx',
link_data: {
link: data.appearance.link
}
}
}, `act_xxxxx`)
.create()
I'm using facebook-js-ads-sdk.
The problem was because of wrong page_id

Mongoose unique validator does not behave like other validators

In my Users schema I have an email field defined as below:
...
email: {
unique: [true, 'A user with that email address exists. The email must be unique.'],
type: String,
lowercase: true,
required: [true, 'A user must have an email address']
},
...
When I leave the email empty while creating a user, I can see my cutomised error message defined in the schema required: [true, 'A user must have an email address']. However, if I pick an email address that is already used by another user, I get a different error, I cannot see my customised message defined in the unique field unique: [true, 'A user with that email address exists. The email must be unique.'].
Error when email is empty (what I find useful as getting the error message is easy): required notice that my error message A user must have an email address is shown.
Error create { MongooseError: User validation failed
at ValidationError (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/error/validation.js:23:11)
at model.Document.invalidate (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/document.js:1486:32)
at /Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/document.js:1362:17
at validate (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/schematype.js:705:7)
at /Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/schematype.js:742:9
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/schematype.js:710:19)
at /Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/document.js:1360:9
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
errors:
{ email:
{ MongooseError: A user must have an email address
at ValidatorError (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/error/validator.js:24:11)
at validate (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/schematype.js:704:13)
at /Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/schematype.js:742:9
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/schematype.js:710:19)
at /Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongoose/lib/document.js:1360:9
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
message: 'A user must have an email address',
name: 'ValidatorError',
properties: [Object],
kind: 'required',
path: 'email',
value: '' } },
message: 'User validation failed',
name: 'ValidationError' }
Error when email has already been used: unique
Error create { MongoError: E11000 duplicate key error collection: stellium-io.users index: email_1 dup key: { : "john#doe.com" }
at Function.MongoError.create (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongodb-core/lib/error.js:31:11)
at toError (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongodb/lib/utils.js:114:22)
at /Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongodb/lib/collection.js:657:23
at handleCallback (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongodb/lib/utils.js:95:56)
at /Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongodb/lib/bulk/unordered.js:465:9
at handleCallback (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongodb/lib/utils.js:95:56)
at resultHandler (/Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongodb/lib/bulk/unordered.js:413:5)
at /Users/fleavamini/Projects/stellium/stellium.io/node_modules/mongodb-core/lib/connection/pool.js:455:18
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
name: 'MongoError',
message: 'E11000 duplicate key error collection: stellium-io.users index: email_1 dup key: { : "john#doe.com" }',
driver: true,
code: 11000,
index: 0,
errmsg: 'E11000 duplicate key error collection: stellium-io.users index: email_1 dup key: { : "john#doe.com" }',
getOperation: [Function],
toJSON: [Function],
toString: [Function] }
Is this the intended behaviour? I want to be able to get my customised error in the unique field and return it to the user trying to create the new user object.
Uniqueness in Mongoose is not a validation parameter(like required),it tells Mongoose to create a unique index in MongoDB for that field.
The uniqueness constraint is handled entirely in the MongoDB server. When you add a document with a duplicate key, the MongoDB server will return the error that you are showing (E11000...).
You have to handle these errors yourself if you want to create custom error messages. The Mongoose documentation (search for "Error Handling Middleware") provides you with an example on how to create custom error handling:
schmea.post('save', function(error, doc, next) {
if (error.name === 'MongoError' && error.code === 11000) {
next(new Error('email must be unique'));
} else {
next(error);
}
});
or you can use this plugin mongoose-unique-validator
(although this doesn't provide you with the specific field for which the uniqueness constraint failed)
The uniqueness constraint is handled entirely in the MongoDB server. When you add a document with a duplicate key, the MongoDB server will return the error that you are showing (E11000...)
You have to handle these errors yourself if you want to create custom error messages.
like:
schmea.post('save',function(err,doc,next){
if (err.name === 'MongoError' && err.code === 11000) {
next(new Error('email must be unique'));
} else {
next(error);
}
});

Sequelize throwing 'id must be unique' on create

new to Sequelize library. From my understanding, 'id' is created automatically by sequelize (and thats what I see in the database). However when I go to 'create' an object it will throw this error:
{ [SequelizeUniqueConstraintError: Validation error]
name: 'SequelizeUniqueConstraintError',
message: 'Validation error',
errors:
[ { message: 'id must be unique',
type: 'unique violation',
path: 'id',
value: '1' } ],
fields: { id: '1' } }
The offending code:
db.Account.create({
email: req.body.email,
password: req.body.password,
allowEmail: req.body.allowEmail,
provider: 'local',
role: 'user'
})
Notice ID is not specified anywhere, neither is it specified in my model definition. Also the query it generates runs fine if I run it in postgres admin:
INSERT INTO "Accounts" ("id","email","role","verifyCode","provider","cheaterScore","isBanned","allowEmail","updatedAt","createdAt") VALUES (DEFAULT,'cat69232#gmail.com','user','','local',0,false,false,'2016-01-27 04:31:54.350 +00:00','2016-01-27 04:31:54.350 +00:00') RETURNING *;
Any ideas to what I could be missing here?
edit:
postgres version: 9.5
stack trace starts here:
/node_modules/sequelize/lib/dialects/postgres/query.js:326
Postgres has a habit of not resetting the next number in the sequence (autoincrement field) after bulk inserts. So if you're doing any pre-filling of the data in an init routine or from a SQL dump file, that's probably your issue.
Check out this post https://dba.stackexchange.com/questions/65662/postgres-how-to-insert-row-with-autoincrement-id

Resources