I want to create an application with NestJs and TypeORM using MongoDB. Let's assume I have an entity with two unique fields besides the ID field
@Entity()
export class Module extends BaseEntity {
@ObjectIdColumn()
public id: ObjectID;
@Column({ unique: true })
public moduleName: string;
@Column({ unique: true })
public displayName: string;
}
When I want to create a new module with a moduleName
or displayName
that already exists I'm getting the following exception error
[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)
So in my catch statement I have to handle the incoming errors. What I have to do is
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 ...
}
}
}
Does TypeORM expose premade exceptions? Is there an enum I could use? What would be a good approach to fetch those TypeORM database errors?
It seems some errors are listed here
https://github.com/typeorm/typeorm/tree/master/src/error
but I can't import them and I didn't find anything about the BulkWriteError
In my catch statement it's possible to do something like
const code: number = error.code;
if (code === 11000) {
throw new ConstraintException(error.errmsg);
}
throw error;
but as you know this isn't the best approach. Also this error object doesn't tell me if the moduleName
or displayName
is invalid. Just within a string
errmsg: 'E11000 duplicate key error collection: test-mongo.module index: UQ_61128bd419e3c3a6d8d7d565ed9 dup key: { moduleName: "firstModule" }',
Do I have to create my own mapping from those error codes to exceptions?
@types/mongodb
which exposesMongoError:: code?: number
. But unfortunately the package doesn't provide enum with list of errors. – mrkosimaConstraintException
. Also as you can see there's a room for a contribution to@types/mongodb
- with enum of error codes :) – mrkosima