feat(api): add async error handling to critical module handlers
Wrap async operations at application layer boundaries with proper try/catch, LoggerService logging, and domain exceptions: - UploadMediaHandler: mediaStorage.upload() error boundary - ExportUserDataHandler: Promise.all() error logging - ForceDeleteUserHandler: $transaction error logging - LoginUserHandler: token generation error boundary - RefreshTokenHandler: token rotation error boundary - CreatePaymentHandler: payment gateway call error boundary Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
@@ -41,23 +41,41 @@ export class ExportUserDataHandler implements ICommandHandler<ExportUserDataComm
|
||||
|
||||
if (!user) throw new NotFoundException('User', command.userId);
|
||||
|
||||
const [agent, listings, payments, subscription, reviews, inquiries, savedSearches, transactions] =
|
||||
await Promise.all([
|
||||
this.prisma.agent.findUnique({ where: { userId: command.userId } }),
|
||||
this.prisma.listing.findMany({
|
||||
where: { sellerId: command.userId },
|
||||
include: { property: { select: { title: true, address: true, district: true, city: true } } },
|
||||
}),
|
||||
this.prisma.payment.findMany({
|
||||
where: { userId: command.userId },
|
||||
select: { id: true, provider: true, type: true, amountVND: true, status: true, createdAt: true },
|
||||
}),
|
||||
this.prisma.subscription.findFirst({ where: { userId: command.userId } }),
|
||||
this.prisma.review.findMany({ where: { userId: command.userId } }),
|
||||
this.prisma.inquiry.findMany({ where: { userId: command.userId } }),
|
||||
this.prisma.savedSearch.findMany({ where: { userId: command.userId } }),
|
||||
this.prisma.transaction.findMany({ where: { buyerId: command.userId } }),
|
||||
]);
|
||||
let agent: unknown | null;
|
||||
let listings: unknown[];
|
||||
let payments: unknown[];
|
||||
let subscription: unknown | null;
|
||||
let reviews: unknown[];
|
||||
let inquiries: unknown[];
|
||||
let savedSearches: unknown[];
|
||||
let transactions: unknown[];
|
||||
|
||||
try {
|
||||
[agent, listings, payments, subscription, reviews, inquiries, savedSearches, transactions] =
|
||||
await Promise.all([
|
||||
this.prisma.agent.findUnique({ where: { userId: command.userId } }),
|
||||
this.prisma.listing.findMany({
|
||||
where: { sellerId: command.userId },
|
||||
include: { property: { select: { title: true, address: true, district: true, city: true } } },
|
||||
}),
|
||||
this.prisma.payment.findMany({
|
||||
where: { userId: command.userId },
|
||||
select: { id: true, provider: true, type: true, amountVND: true, status: true, createdAt: true },
|
||||
}),
|
||||
this.prisma.subscription.findFirst({ where: { userId: command.userId } }),
|
||||
this.prisma.review.findMany({ where: { userId: command.userId } }),
|
||||
this.prisma.inquiry.findMany({ where: { userId: command.userId } }),
|
||||
this.prisma.savedSearch.findMany({ where: { userId: command.userId } }),
|
||||
this.prisma.transaction.findMany({ where: { buyerId: command.userId } }),
|
||||
]);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Failed to export user data for ${command.userId}: ${error instanceof Error ? error.message : error}`,
|
||||
error instanceof Error ? error.stack : undefined,
|
||||
'ExportUserDataHandler',
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.logger.log(`User data exported for ${command.userId}`, 'ExportUserDataHandler');
|
||||
|
||||
|
||||
@@ -15,7 +15,16 @@ export class ForceDeleteUserHandler implements ICommandHandler<ForceDeleteUserCo
|
||||
if (!user) throw new NotFoundException('User', command.userId);
|
||||
if (user.deletedAt) return { message: 'Tài khoản đã bị xóa' };
|
||||
|
||||
await this.anonymizeAndDelete(command.userId);
|
||||
try {
|
||||
await this.anonymizeAndDelete(command.userId);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Force delete transaction failed for user ${command.userId}: ${error instanceof Error ? error.message : error}`,
|
||||
error instanceof Error ? error.stack : undefined,
|
||||
'ForceDeleteUserHandler',
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.logger.log(
|
||||
`User ${command.userId} force-deleted by admin ${command.adminId}: ${command.reason}`,
|
||||
|
||||
@@ -1,16 +1,29 @@
|
||||
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
|
||||
import { type LoggerService, UnauthorizedException } from '@modules/shared';
|
||||
import { type TokenService, type TokenPair } from '../../../infrastructure/services/token.service';
|
||||
import { LoginUserCommand } from './login-user.command';
|
||||
|
||||
@CommandHandler(LoginUserCommand)
|
||||
export class LoginUserHandler implements ICommandHandler<LoginUserCommand> {
|
||||
constructor(private readonly tokenService: TokenService) {}
|
||||
constructor(
|
||||
private readonly tokenService: TokenService,
|
||||
private readonly logger: LoggerService,
|
||||
) {}
|
||||
|
||||
async execute(command: LoginUserCommand): Promise<TokenPair> {
|
||||
return this.tokenService.generateTokenPair({
|
||||
sub: command.userId,
|
||||
phone: command.phone,
|
||||
role: command.role,
|
||||
});
|
||||
try {
|
||||
return await this.tokenService.generateTokenPair({
|
||||
sub: command.userId,
|
||||
phone: command.phone,
|
||||
role: command.role,
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Token generation failed for user ${command.userId}: ${error instanceof Error ? error.message : error}`,
|
||||
error instanceof Error ? error.stack : undefined,
|
||||
'LoginUserHandler',
|
||||
);
|
||||
throw new UnauthorizedException('Không thể tạo phiên đăng nhập, vui lòng thử lại');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Inject } from '@nestjs/common';
|
||||
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
|
||||
import { UnauthorizedException } from '@modules/shared';
|
||||
import { type LoggerService, UnauthorizedException } from '@modules/shared';
|
||||
import { USER_REPOSITORY, type IUserRepository } from '../../../domain/repositories/user.repository';
|
||||
import { type TokenService, type TokenPair } from '../../../infrastructure/services/token.service';
|
||||
import { RefreshTokenCommand } from './refresh-token.command';
|
||||
@@ -10,10 +10,22 @@ export class RefreshTokenHandler implements ICommandHandler<RefreshTokenCommand>
|
||||
constructor(
|
||||
private readonly tokenService: TokenService,
|
||||
@Inject(USER_REPOSITORY) private readonly userRepo: IUserRepository,
|
||||
private readonly logger: LoggerService,
|
||||
) {}
|
||||
|
||||
async execute(command: RefreshTokenCommand): Promise<TokenPair> {
|
||||
const rotated = await this.tokenService.rotateRefreshToken(command.refreshToken);
|
||||
let rotated: Awaited<ReturnType<TokenService['rotateRefreshToken']>>;
|
||||
try {
|
||||
rotated = await this.tokenService.rotateRefreshToken(command.refreshToken);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Token rotation failed: ${error instanceof Error ? error.message : error}`,
|
||||
error instanceof Error ? error.stack : undefined,
|
||||
'RefreshTokenHandler',
|
||||
);
|
||||
throw new UnauthorizedException('Không thể làm mới phiên đăng nhập');
|
||||
}
|
||||
|
||||
if (!rotated) {
|
||||
throw new UnauthorizedException('Refresh token không hợp lệ hoặc đã hết hạn');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user