node.js - 如何使用 Sequelize 特定错误?

标签 node.js exception sequelize.js

你如何导入 Sequelize 错误?
我想使用诸如 SequelizeUniqueConstraintError) 之类的特定错误进行错误处理。

try {
  query...
} catch(e){
  if (e instanceof SequelizeUniqueConstraintError) { 
    next(new ResourceError(e.toString(), 401))
  } else {
    next(new ResourceError(e.toString(), 500))
  }
}
我收到 SequelizeUniqueConstraintError is not defined ,但我似乎无法浏览 sequelize 实例以找到任何错误类?

最佳答案

检查 SequelizeUniqueConstraintErrorsource code 。名为 UniqueConstraintError 的类。 SequelizeUniqueConstraintErrorname 属性的值。它是 而不是 一个 JavaScript 类。所以你应该使用 UniqueConstraintError
例如。

import { UniqueConstraintError } from 'sequelize';

try {
  throw new UniqueConstraintError({ message: 'test unique constraint' });
} catch (e) {
  if (e instanceof UniqueConstraintError) {
    console.log(401);
  } else {
    console.log(500);
  }
}
执行结果:
401
包版本:"sequelize": "^5.21.3"

关于node.js - 如何使用 Sequelize 特定错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64215137/

相关文章:

node.js - Express 4 压缩

java - 为什么我会收到 java.nio.BufferOverflowException

javascript - 序列化 ORM - 错误 : not returning database values

javascript - 如何 npm install only devDependencies with node 8.7.x?

javascript - Module.exports 函数为变量返回 'undefined'

node.js - 如何在谷歌云平台上部署strapi?

c++ - 在递归 C++ 函数中捕获 "Stack Overflow"异常

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

node.js - Typeorm Migration 用于自引用迁移

postgresql - 谷歌云 sql PostgreSQL 9.6 ST_GeomFromGeoJSON JSON-C 错误