Refactor error handling in controllers and services

This commit is contained in:
faris Aljohari
2024-04-14 11:28:52 +03:00
parent 53628236a6
commit d92ae03eac
10 changed files with 287 additions and 308 deletions

View File

@ -53,8 +53,12 @@ export class CommunityService {
},
relations: ['spaceType'],
});
if (!community) {
throw new HttpException('Community not found', HttpStatus.NOT_FOUND);
if (
!community ||
!community.spaceType ||
community.spaceType.type !== 'community'
) {
throw new BadRequestException('Invalid community UUID');
}
return {
uuid: community.uuid,
@ -64,42 +68,51 @@ export class CommunityService {
type: community.spaceType.type,
};
} catch (err) {
throw new HttpException(
err.message,
err.status || HttpStatus.INTERNAL_SERVER_ERROR,
);
if (err instanceof BadRequestException) {
throw err; // Re-throw BadRequestException
} else {
throw new HttpException('Community not found', HttpStatus.NOT_FOUND);
}
}
}
async getCommunityChildByUuid(
communityUuid: string,
getCommunityChildDto: GetCommunityChildDto,
): Promise<CommunityChildInterface> {
const { includeSubSpaces, page, pageSize } = getCommunityChildDto;
try {
const { includeSubSpaces, page, pageSize } = getCommunityChildDto;
const space = await this.spaceRepository.findOneOrFail({
where: { uuid: communityUuid },
relations: ['children', 'spaceType'],
});
const space = await this.spaceRepository.findOneOrFail({
where: { uuid: communityUuid },
relations: ['children', 'spaceType'],
});
if (space.spaceType.type !== 'community') {
throw new HttpException('Community not found', HttpStatus.NOT_FOUND);
if (!space || !space.spaceType || space.spaceType.type !== 'community') {
throw new BadRequestException('Invalid community UUID');
}
const totalCount = await this.spaceRepository.count({
where: { parent: { uuid: space.uuid } },
});
const children = await this.buildHierarchy(
space,
includeSubSpaces,
page,
pageSize,
);
return {
uuid: space.uuid,
name: space.spaceName,
type: space.spaceType.type,
totalCount,
children,
};
} catch (err) {
if (err instanceof BadRequestException) {
throw err; // Re-throw BadRequestException
} else {
throw new HttpException('Community not found', HttpStatus.NOT_FOUND);
}
}
const totalCount = await this.spaceRepository.count({
where: { parent: { uuid: space.uuid } },
});
const children = await this.buildHierarchy(
space,
includeSubSpaces,
page,
pageSize,
);
return {
uuid: space.uuid,
name: space.spaceName,
type: space.spaceType.type,
totalCount,
children,
};
}
private async buildHierarchy(