From 4dc05ac1809ba18968210e1cac21dd03dc973819 Mon Sep 17 00:00:00 2001 From: sdraris Date: Mon, 25 Aug 2025 10:49:10 +0200 Subject: [PATCH] interceptors + filters added --- src/common/filters/all_exceptions.filters.ts | 27 +++++++++++++++++++ .../interceptors/transform.interceptor.ts | 15 +++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/common/filters/all_exceptions.filters.ts create mode 100644 src/common/interceptors/transform.interceptor.ts diff --git a/src/common/filters/all_exceptions.filters.ts b/src/common/filters/all_exceptions.filters.ts new file mode 100644 index 0000000..4d46609 --- /dev/null +++ b/src/common/filters/all_exceptions.filters.ts @@ -0,0 +1,27 @@ +import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from "@nestjs/common"; + +@Catch() +export class AllExceptionsFilter implements ExceptionFilter { + catch(exception: unknown, host: ArgumentsHost) { + const ctx = host.switchToHttp(); + const response = ctx.getResponse(); + const request = ctx.getRequest(); + const status = + exception instanceof HttpException + ? exception.getStatus() + : HttpStatus.INTERNAL_SERVER_ERROR; + + const message = + exception instanceof HttpException + ? exception.getResponse() + : { message: 'Internal server error' }; + + response.status(status).json({ + success: false, + statusCode: status, + timestamp: new Date().toISOString(), + path: request.url, + message, + }); + } +} \ No newline at end of file diff --git a/src/common/interceptors/transform.interceptor.ts b/src/common/interceptors/transform.interceptor.ts new file mode 100644 index 0000000..300de4a --- /dev/null +++ b/src/common/interceptors/transform.interceptor.ts @@ -0,0 +1,15 @@ +import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common"; +import { map, Observable, timestamp } from "rxjs"; + +@Injectable() +export class TransformInterceptor implements NestInterceptor { + intercept(context: ExecutionContext, next: CallHandler): Observable { + return next.handle().pipe( + map((data) => ({ + success: true, + timestamp: new Date().toISOString(), + data + })), + ); + } +} \ No newline at end of file