Skip to content

Commit

Permalink
feat: add Interceptor for error logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Jiwon-Woo committed Jan 11, 2024
1 parent 73ff336 commit bd7a973
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/common/interceptor/log.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import {
CallHandler,
ExecutionContext,
HttpException,
Injectable,
Logger,
NestInterceptor,
} from '@nestjs/common';
import { Observable, catchError } from 'rxjs';
import { ServiceException } from '../exception/service.exception';
import { UnknownException } from '../exception/unknown.exception';
import { SlackService } from 'nestjs-slack';
import { Message } from 'slack-block-builder';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class LogInterceptor implements NestInterceptor {
private readonly logger = new Logger(LogInterceptor.name);

constructor(
private slackService: SlackService,
private configService: ConfigService,
) {}

intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
// const start = new Date();
const request = context.switchToHttp().getRequest();

return next.handle().pipe(
catchError((err) => {
const log = `${request.method} ${request.url} - ${err.stack}`;
this.logger.error(log);
if (err instanceof ServiceException || err instanceof HttpException) {
throw err;
}
this.slackService.postMessage(
Message({
text: log,
channel: this.configService.get('slack.jiphyeonjeonChannel'),
}).buildToObject(),
);
throw new UnknownException();
}),
// tap((observable) => {
// const end = new Date();
// }),
);
}
}

0 comments on commit bd7a973

Please sign in to comment.