Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions libs/common/src/decorators/transactional.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { UseInterceptors } from '@nestjs/common';
import { TransactionInterceptor } from '../interceptors/transaction.interceptor';

export function Transactional(): MethodDecorator {
return UseInterceptors(TransactionInterceptor);
}
29 changes: 9 additions & 20 deletions libs/common/src/filters/http-exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,34 @@ import {
ExceptionFilter,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ErrorHandlerService } from 'src/modules/error-handler/error-handler.service';

/**
* Normalizes error responses into the same envelope style used for success
* responses, and logs unexpected (non-HTTP) errors for diagnosis.
*/
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
private readonly logger = new Logger(AllExceptionsFilter.name);
constructor(private readonly errorHandlerService: ErrorHandlerService) {}

catch(exception: unknown, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();

const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const appError = this.errorHandlerService.handle(exception);

const message =
exception instanceof HttpException
? exception.getResponse()
: 'Internal server error';
const isProduction = process.env.NODE_ENV === 'production';

if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
this.logger.error(
`Unhandled exception on ${request.method} ${request.url}`,
exception instanceof Error ? exception.stack : String(exception),
);
}

response.status(status).json({
response.status(appError.getStatus()).json({
success: false,
statusCode: status,
statusCode: appError.getStatus(),
path: request.url,
error: typeof message === 'string' ? { message } : message,
error: isProduction
? { message: 'An unexpected error occurred.' }
: appError.toDetail(),
timestamp: new Date().toISOString(),
});
}
Expand Down
40 changes: 40 additions & 0 deletions libs/common/src/interceptors/transaction.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { InjectConnection } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { Observable } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable()
export class TransactionInterceptor implements NestInterceptor {
constructor(@InjectConnection() private readonly connection: Connection) {}

async intercept(
context: ExecutionContext,
next: CallHandler,
): Promise<Observable<any>> {
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();

// Attach the queryRunner to the request object
const request = context.switchToHttp().getRequest();
request.queryRunner = queryRunner;

return next.handle().pipe(
tap(async () => {
await queryRunner.commitTransaction();
await queryRunner.release();
}),
catchError(async (err) => {
await queryRunner.rollbackTransaction();
await queryRunner.release();
throw err;
}),
);
}
}
Loading
Loading