Antonio Costa
Antonio Costa

Reputation: 193

Capture error in sequelize model

i have this model defined in sequelize:

"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');

module.exports = function (sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: DataTypes.STRING,
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        isEmail: true
      },
      unique: {
        args: true,
        msg: 'Email address already in use!'
      }
    },
    password: DataTypes.STRING
  }, {
      classMethods: {
        generateHash: function (password) {
          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },

      },
      instanceMethods: {
        validPassword: function (password) {
          return bcrypt.compareSync(password, this.password);
        },
        checkEmailExists: function (email) {
          return email == this.email
        }
      }


    });



  return User;
}

i need to detect if a email aleady exist so i put a custom validation on the email, but then in my routing i have this:

var express = require('express');
var User = require('../../models').User;
var router = express.Router();
var sequelize = require('../../models/index');


/* GET users listing. */
router.post('/', function (req, res, next) {

  if (JSON.stringify(req.body) == "{}") {
    return res.status(400).json({ Error: "Register request body is empty" });
  }
  if (!req.body.email || !req.body.username || !req.body.password) {
    return res.status(400).json({ Error: "Missing fields for registration" });
  }

  var password = User.generateHash(req.body.password);


  User.create({
    username: req.body.username,
    email: req.body.email,
    password: password
  }).then(function () {
    return res.status(200).json({ message: "user created" });
  }).catch(function (err) {
    return res.status(400).json({ message: "issues trying to connect to database" });
  })

});


module.exports = router;

seems like it is entering the catch because it detects that the email already exist, but i want to display the message that is inside the model and not that catch that can mean something else, how can i display it there in my routing?

Upvotes: 4

Views: 4858

Answers (2)

Ahmad Zahabi
Ahmad Zahabi

Reputation: 1268

in Role model:

name: {
    type: DataTypes.STRING,
    validate: {
        len: [3, 5]
    }
},

and then

const {ValidationError} = require('sequelize');
async function test() {
    try {
        var item = await Role.build({code: 'SSA1', name: 'testtttt'});
        await item.validate();
         // validation passed
        await item.save(); 
        console.log('object created successfully');
    }catch (e) {
        if(e instanceof ValidationError){
            return console.error( 'Captured validation error: ', e.errors[0].message);
        }
        console.error(e);
    }
}
test();

log:

Captured validation error: Validation len on name failed

Upvotes: 8

Barys Malaichyk
Barys Malaichyk

Reputation: 164

checkout err object, it is SequelizeError instance, where you can find your model-defined msg

Upvotes: 1

Related Questions