Skip to content

Commit

Permalink
feat : exceptionfilter
Browse files Browse the repository at this point in the history
  • Loading branch information
kangjuhyup committed Oct 9, 2024
1 parent 92e2686 commit b169e04
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 3 deletions.
10 changes: 9 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { CommentModule } from './domain/comment/comment.module';
import { ConfigModule } from '@nestjs/config';
import { DatabaseModule } from './database/database.module';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { ExceptionInterceptor } from './common/exception/interceptor';

@Module({
imports: [
Expand All @@ -23,6 +25,12 @@ import { EventEmitterModule } from '@nestjs/event-emitter';
CommentModule,
],
controllers: [AppController],
providers: [AppService],
providers: [
{
provide: APP_INTERCEPTOR,
useClass: ExceptionInterceptor,
},
AppService,
],
})
export class AppModule {}
2 changes: 1 addition & 1 deletion src/common/exception/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ export class BaseExceptionFilter implements ExceptionFilter {
private logger = new Logger(BaseExceptionFilter.name);

catch(error: any, host: ArgumentsHost) {
this.logger.error(error);
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = error.status;
this.logger.error(error);
if (status >= 400 && status < 500) {
response.status(status).send({ result: false, error: error.response });
} else {
Expand Down
19 changes: 19 additions & 0 deletions src/common/exception/interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ExceptionInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
catchError(async (error) => {
//TODO: 알 수 없는 에러 발생 시 알림 전송
return Promise.reject(error);
}),
);
}
}
3 changes: 2 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { BaseExceptionFilter, NestFactory } from '@nestjs/core';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import 'dotenv/config';
import { ValidationPipe } from '@nestjs/common';
import { BaseExceptionFilter } from './common/exception/filter';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
Expand Down

0 comments on commit b169e04

Please sign in to comment.