You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 08:04:59