Get .findOrCreate () error

I am using Sequelize as an ORM. Here is my user model:

 ### User model ### User = exports.User = globals.sequelize.define "User", username: globals.Sequelize.STRING email: type: globals.Sequelize.STRING validate: isEmail: true hash: globals.Sequelize.STRING salt: globals.Sequelize.STRING(512) fname: globals.Sequelize.STRING lname: globals.Sequelize.STRING country: globals.Sequelize.STRING 

I save user:

 globals.models.User.findOrCreate username: "johny" password: "pass" email: "johny93[###]example.com" .success (user, created)-> console.log user.values res.send 200 .error -> console.log err # how to catch this? res.send 502 

If the email is valid (email: " johny93@example.com "), everything works fine. But if the email fails verification (as in the example above), I get an insert error. How to catch the type of error? .error method cannot get any error parameters.

+7
source share
3 answers

sequelize will pass the error as a parameter to the error function.

Javascript

 User.findOrCreate({username: "johny",password: "pass",email: "johny93[###]example.com"}) .success(function(user, created){ console.log(user.values); res.send(200); }) .error(function(err){ console.log('Error occured' + err); }) 

CoffeScript

 globals.models.User.findOrCreate username: "johny" password: "pass" email: "johny93[###]example.com" .success (user, created)-> console.log user.values res.send 200 .error (error)-> console.log error # how to catch this? res.send 502 
+7
source share
  User.findOrCreate({ where: { username: "johny", password: "pass", email: "johny93[###]example.com" }, defaults: { //properties to be created } }).then(function(user){ var created = user[1]; user = user[0]; console.log(user.values); }).fail(function(err){ console.log('Error occured', err); }); 

https://github.com/sequelize/sequelize/wiki/Upgrading-to-2.0

EDIT: as @Domi pointed out, the best way is to use "distribution" instead of "then"

 User.findOrCreate({ where: { username: "johny", password: "pass", email: "johny93[###]example.com" }, defaults: { //properties to be created } }).spread(function(user, created){ console.log(user.values); }).fail(function(err){ console.log('Error occured', err); }); 
+13
source share

Sequelize 2.0 will change the syntax and will now

 User.findOrCreate({ where: { username: 'johny', password: 'pass', email: 'johny93[###]example.com' } }).then(function (user) { res.send(200); }).catch(function (err) { console.log(err); res.send(502); }); 
+3
source share

All Articles