类型安全 TypeORM 异常错误处理

hrp*_*xQ4 7 mongodb typeorm nestjs

我想使用 MongoDB 创建一个带有 NestJs 和 TypeORM 的应用程序。假设我有一个实体,除了 ID 字段之外还有两个唯一字段

@Entity()
export class Module extends BaseEntity {
  @ObjectIdColumn()
  public id: ObjectID;

  @Column({ unique: true })
  public moduleName: string;

  @Column({ unique: true })
  public displayName: string;
}
Run Code Online (Sandbox Code Playgroud)

当我想创建一个moduleNamedisplayName已经存在的新模块时,我收到以下异常错误

[Nest] 6624   - 2020-02-20 16:31:36   [ExceptionsHandler] E11000 duplicate key error collection: test-mongo.module index: UQ_61128bd419e3c3a6d8d7d565ed9 dup key: { moduleName: "firstModule" } +23849ms
BulkWriteError: E11000 duplicate key error collection: test-mongo.module index: UQ_61128bd419e3c3a6d8d7d565ed9 dup key: { moduleName: "firstModule" }
    at OrderedBulkOperation.handleWriteError (C:\Users\mhermsen\Gitlab Repositories\server\node_modules\mongodb\lib\bulk\common.js:1210:11)
    at resultHandler (C:\Users\mhermsen\Gitlab Repositories\server\node_modules\mongodb\lib\bulk\common.js:519:23)
    at C:\Users\mhermsen\Gitlab Repositories\server\node_modules\mongodb\lib\core\connection\pool.js:404:18
    at processTicksAndRejections (internal/process/task_queues.js:76:11)
Run Code Online (Sandbox Code Playgroud)

所以在我的 catch 语句中,我必须处理传入的错误。我必须做的是

try {
  // create module
} catch (error) {
  if (/* error is TypeORM error */) {
    if (/* wrong attribute is the module name */) {
      // module name exists ...
    }

    if (/* wrong attribute is the display name */) {
      // display name exists ...
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

TypeORM 是否暴露预制异常?有我可以使用的枚举吗?获取这些 TypeORM 数据库错误的好方法是什么?


这里似乎列出了一些错误

https://github.com/typeorm/typeorm/tree/master/src/error

但我无法导入它们并且我没有找到任何关于 BulkWriteError


在我的 catch 语句中,可以执行类似的操作

const code: number = error.code;

if (code === 11000) {
  throw new ConstraintException(error.errmsg);
}

throw error;
Run Code Online (Sandbox Code Playgroud)

但正如你所知,这不是最好的方法。此外,此错误对象不会告诉我moduleNameordisplayName是否无效。就在一个字符串中

errmsg: 'E11000 重复键错误集合: test-mongo.module index: UQ_61128bd419e3c3a6d8d7d565ed9 dup key: { moduleName: "firstModule" }',

我是否必须创建自己的从这些错误代码到异常的映射?