-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add Interceptor for error logging
- Loading branch information
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
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
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(); | ||
// }), | ||
); | ||
} | ||
} |