Skip to content

Instantly share code, notes, and snippets.

@mramirid
Last active March 28, 2023 06:22
Show Gist options
  • Save mramirid/483782de0eff46257de02600f905e9f9 to your computer and use it in GitHub Desktop.
Save mramirid/483782de0eff46257de02600f905e9f9 to your computer and use it in GitHub Desktop.
NestJS & TypeORM QueryFailedError Exception Filter
import { PG_UNIQUE_VIOLATION } from '@drdgvhbh/postgres-error-codes';
import {
ArgumentsHost,
Catch,
ConflictException,
HttpException,
InternalServerErrorException,
} from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { QueryFailedError } from 'typeorm';
@Catch(QueryFailedError)
export class QueryFailedExceptionFilter extends BaseExceptionFilter {
override catch(exception: QueryFailedError, host: ArgumentsHost) {
let httpException: HttpException;
switch (exception.driverError.code) {
case PG_UNIQUE_VIOLATION:
httpException = new ConflictException(exception.message);
break;
default:
httpException = new InternalServerErrorException(exception.message);
}
super.catch(httpException, host);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment