Created
March 4, 2021 21:50
-
-
Save LucasFsc/6ac0d0733b50f2960aa67ee4fb53be87 to your computer and use it in GitHub Desktop.
NestJS MongoError filter exception (Typescript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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