在续集模型中捕获错误

时间:2017-05-14 16:48:28

标签: javascript node.js postgresql express sequelize.js

我在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;
}

我需要检测是否存在电子邮件,所以我在电子邮件中进行了自定义验证,但是在我的路由中我有这个:

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;

似乎它正在进入捕获因为它检测到电子邮件已经存在,但我想显示模型内部的消息而不是那些可能意味着其他东西的捕获,我如何在我的路由中显示它?

2 个答案:

答案 0 :(得分:3)

在角色模型中:

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

然后

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();

日志:

捕获的验证错误:对名称的len验证失败

答案 1 :(得分:0)

checkout err对象,它是SequelizeError实例,在这里你可以找到模型定义的msg