【发布时间】:2021-10-05 19:29:43
【问题描述】:
(我是这方面的新手) 我正在为我的应用程序使用nestjs+typeorm+postgres。 db中有一个“community”列,它使用UUID类型作为id。 所以在我的应用程序中,我编写了一个基本逻辑来从给定的查询 ID 中找出确切的社区,如果找不到则返回 404,但是如果我在请求 URL 中发送非 UUID 类型,它会抛出 500 说非 UUID 类型并且应用程序崩溃了。 为什么我没有得到正确的 404? 我确实尝试过避免应用程序崩溃,但应该有办法返回正确的 404。
我的 Community.service.ts 文件(需要的部分):
// GET: gets the specified community if id provided in
// query, otherwise returns all communities
public async getCommunity(id?: string): Promise<Community | Community[]> {
if (!id) {
const communities = await this.communityRepository.find();
return communities;
} else {
const community = this.communityRepository.findOne(id);
return community;
}
}
这里是 community.controller.ts(需要的部分):
@Get('')
async getAllCommunities(
@Query('id') id?: string,
): Promise<Community[] | Community> {
try {
const communities = await this.communityService.getCommunity(id);
if (!communities) {
throw new NotFoundException();
}
return communities;
} catch (err) {
return err;
}
}
【问题讨论】:
-
首先,您从
this.communityRepository.findOne(id);中缺少await。如果id不是undefined,我建议你安装class-validator并使用isUUID()验证器。这样做你可以检查 id 是否是一个有效的 UUID,如果没有抛出错误。 -
感谢 CarloCorradini 我已经安装了类验证器,但不知道 UUID 检查
-
很好,将其添加到答案中?
标签: typescript postgresql backend nestjs typeorm