Skip to content

Instantly share code, notes, and snippets.

@LucasFsc
Created March 4, 2021 21:50
Show Gist options
  • Save LucasFsc/6ac0d0733b50f2960aa67ee4fb53be87 to your computer and use it in GitHub Desktop.
Save LucasFsc/6ac0d0733b50f2960aa67ee4fb53be87 to your computer and use it in GitHub Desktop.
NestJS MongoError filter exception (Typescript)
import { Catch, ConflictException, ExceptionFilter } from '@nestjs/common'
import { MongoError } from 'mongodb'
@Catch(MongoError)
export class MongoExceptionFilter implements ExceptionFilter {
catch(exception: MongoError) {
switch (exception.code) {
case 11000:
// get error param key and value
const [key, value] = Object.entries({ ...exception }?.['keyValue'])?.[0]
if (key && value) {
throw new ConflictException(`${key} ${value} is already in use`)
} else {
throw new ConflictException()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment