Skip to content

Instantly share code, notes, and snippets.

@mateothegreat
Created June 21, 2023 17:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mateothegreat/c82c9413830fe374ef8ab579747aea88 to your computer and use it in GitHub Desktop.
Save mateothegreat/c82c9413830fe374ef8ab579747aea88 to your computer and use it in GitHub Desktop.
nest.js exception filtering
import { ArgumentsHost, Catch, ExceptionFilter, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
@Catch()
export class GlobalExceptionsFilter implements ExceptionFilter {
public catch(exception: any, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response: Response = ctx.getResponse<Response>();
const clazz = exception.constructor.name;
if (process.env.DEBUG) {
console.error(`GlobalExceptionsFilter.catch(): ${JSON.stringify(exception)}`);
console.error(`GlobalExceptionsFilter.catch(): class name = ${clazz}`);
}
if (clazz === 'UnauthorizedException') {
response.sendStatus(401);
} else if (clazz === 'BadRequestException') {
response.sendStatus(400);
} else if (clazz === 'ResourceNotFoundException') {
response.sendStatus(exception.status);
} else if (clazz === 'ResourceForbiddenException') {
response.sendStatus(exception.status);
} else if (clazz === 'EntityNotFoundError') {
response.sendStatus(HttpStatus.NOT_FOUND);
} else if (clazz === 'ResourceAlreadyExistsException') {
response.sendStatus(exception.status);
} else if (clazz === 'QueryFailedError') {
if (exception.message.indexOf('duplicate key') >= -1) {
response.sendStatus(HttpStatus.CONFLICT);
}
} else if (exception.status) {
response.sendStatus(exception.status);
} else {
response.sendStatus(500);
}
}
}
import { ArgumentsHost, Catch, ConflictException, ExceptionFilter } from '@nestjs/common';
@Catch()
export class GlobalExceptionsFilter implements ExceptionFilter {
public catch(exception: any, host: ArgumentsHost): void {
// const log = {
// date: new Date(),
// source: request.ip,
// url: request.url,
// method: request.method,
// headers: request.headers,
// body: JSON.stringify(request.body).slice(0, 1000),
// exception: exception.message,
// status: exception.status,
// clazz: clazz
// };
// console.log(log);
// if (process.env.DEBUG) {
// console.error(`GlobalExceptionsFilter.catch()`, log);
// }
console.log(exception.code);
if (exception.code === 'P2002') {
throw new ConflictException();
}
}
}
require('dotenv').config({ path: `.env.${process.env.ENVIRONMENT || 'local'}` });
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { GraphQLSchemaFactory } from '@nestjs/graphql';
import * as fs from 'fs';
import { printSchema } from 'graphql/utilities';
import { GlobalExceptionsFilter } from './Lib/GlobalExceptionsFilter';
import { AppModule } from './module';
import { RESOLVERS } from './resolvers';
export let app: INestApplication = null;
async function bootstrap() {
app = await NestFactory.create(AppModule, {
snapshot: true
});
app.useGlobalFilters(new GlobalExceptionsFilter());
await app.listen(3000);
const gqlSchemaFactory = app.get(GraphQLSchemaFactory);
const schema = await gqlSchemaFactory.create(RESOLVERS);
fs.writeFileSync('schema.graphql', printSchema(schema));
}
void bootstrap();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment