如何在 Express API 中显示 Sequelize 验证错误消息

ana*_*man 3 javascript orm node.js express sequelize.js

我在带有运行 MySQL 的 Sequelize ORM 的 Node.js/Express API 中使用了这个组织模型。当我违反validation下面第一个代码示例中的 2-100 个字符规则时,我err从第二个代码示例中的 catch 块中获得了经典项,它不包含任何有关验证错误的信息。

我想显示您可以validation { len: { msg: ...}}在模型中看到的验证错误消息。至少console.log吧,然后再显示给最终用户。

但是,Sequelize 手册和我能找到的任何其他信息都没有解释我如何使用此自定义错误消息。所以我的问题是如何利用它并显示它。

模型:

'use strict'

const { Sequelize, DataTypes } = require('sequelize');
const db = require('./../config/db.js')

const Organization = db.define('organizations', {
  id: {
    type: DataTypes.UUID,
    defaultValue: Sequelize.UUIDV4,
    primaryKey: true,
    allowNull: false,
    unique: true,
    validate: {
      isUUID: {
        args: 4,
        msg: 'The ID must be a UUID4 string'
      }
    }
  },
  name: {
    type: DataTypes.STRING,
    required: true,
    allowNull: false,
    validate: {
      len: {
        args: [2, 100],
        msg: 'The name must contain between 2 and 100 characters.' // Error message I want to display
      }
    }
  },
  created_at: {
    type: DataTypes.DATE,
    required: true,
    allowNull: false
  },
  updated_at: {
    type: DataTypes.DATE,
    required: true,
    allowNull: false
  },
  deleted_at: {
    type: DataTypes.DATE
  }
},
{
  underscored: true,
  paranoid: true,
  tableName: 'organizations',
  updatedAt: 'updated_at',
  createdAt: 'created_at',
  deletedAt: 'deleted_at'
})

module.exports = Organization
Run Code Online (Sandbox Code Playgroud)

控制器:

/**
 *  @description Create new organization
 *  @route POST /api/v1/organizations
 */

exports.createOrganization = async (req, res, next) => {
  try {
    const org = await Organization.create(
      req.body,
      {
        fields: ['name', 'type']
      })
    return res.status(200).json({
      success: true,
      data: {
        id: org.id,
        name: org.name
      },
      msg: `${org.name} has been successfully created.`
    })
  } catch (err) {
    next(new ErrorResponse(`Sorry, could not save the new organization`, 404))

// ^ This is the message I get if I violate the validation rule ^

  }
}
Run Code Online (Sandbox Code Playgroud)

用于验证和约束的 Sequelize 文档可在此处找到:https ://sequelize.org/master/manual/validations-and-constraints.html

验证建立在 Validatorjs ( https://github.com/validatorjs/validator.js ) 上,不幸的是,它也缺乏有关使用验证对象的实用信息。我想这意味着它必须是不言自明的,但是由于我是菜鸟,所以我迷路了。

Roh*_*bre 8

我在firstName现场的本地项目上尝试了相同的验证,我可能会遇到这样的续集错误

console.log('err.name', err.name);
console.log('err.message', err.message);
console.log('err.errors', err.errors);
err.errors.map(e => console.log(e.message)) // The name must contain between 2 and 100 characters.
Run Code Online (Sandbox Code Playgroud)

验证输出

如您所见,您可以检查是否err.nameSequelizeValidationError,然后循环遍历err.errors数组并获取message字段,path其他属性也在那里。

错误显示示例:

const errObj = {};
err.errors.map( er => {
   errObj[er.path] = er.message;
})
console.log(errObj);
Run Code Online (Sandbox Code Playgroud)

你会得到一个像

{ 
  firstName: 'The firstName must contain between 2 and 100 characters.',
  lastName: 'The lastName must contain between 2 and 100 characters.' 
}
Run Code Online (Sandbox Code Playgroud)