NestJS按ID查询图书接口Postman测试返回异常问题咨询
问题原因及解决方案
核心原因
Mongoose的findById方法存在两种行为逻辑:
- 当传入的ID格式不合法(比如长度不符、包含非十六进制字符):会直接抛出异常,触发代码里的
catch块,返回404响应,这符合你的预期。 - 当传入的ID格式合法但不存在(比如长度正确、字符均为十六进制,但数据库中无对应文档):不会抛出异常,仅返回
null。你的代码未对这个null结果做判断,直接返回给Controller,因此接口返回200 OK,但响应体为空(或null)。
修复方案
在Service的findBookById方法中,添加查询结果的非空判断,当结果为null时主动抛出404异常:
async findBookById(id: string): Promise<Book> { try { const bookFounded = await this.bookModel.findById(id); // 新增非空判断,查询不到则抛出异常 if (!bookFounded) { throw new HttpException("Book not found!", HttpStatus.NOT_FOUND); } return bookFounded; } catch (error) { throw new HttpException("Book not found!", HttpStatus.NOT_FOUND); } }
如果需要区分「ID格式错误」和「图书不存在」的场景,可在catch块中识别异常类型做差异化处理:
async findBookById(id: string): Promise<Book> { try { const bookFounded = await this.bookModel.findById(id); if (!bookFounded) { throw new HttpException("Book not found!", HttpStatus.NOT_FOUND); } return bookFounded; } catch (error) { // 识别Mongoose的CastError(ID格式错误) if (error.name === 'CastError') { throw new HttpException("Invalid book ID format!", HttpStatus.BAD_REQUEST); } throw new HttpException("Book not found!", HttpStatus.NOT_FOUND); } }
内容的提问来源于stack exchange,提问作者Dev Taqasar Walayat
相关产品推荐
相关产品推荐

