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

调用getPersonById无ID匹配时如何触发catch块返回指定错误消息

你之前的修改版存在两个问题:

  1. 调用res.json()直接返回字符串时,JSON序列化会自动给字符串包裹双引号,就是你看到的带引号的返回结果
  2. 没有在if判断分支后终止函数执行,后续的res.json(person)依然会运行,会触发「无法在响应已发送后设置响应头」的报错

解决方案1:主动抛错触发catch块逻辑

你只需要在判断到无匹配ID时主动抛出错误,代码就会直接跳转进入catch分支,复用你预设的返回逻辑:

router.get('/:id', async (req, res) => {
  checkString(req.params.id)
  try {
    const person = await peopleData.getPersonById(req.params.id);
    if(!person) {
      // 主动抛错,直接进入catch块
      throw new Error()
    }
    res.json(person);
  } catch (e) {
    res.status(404).json({ message: 'There is no person with that ID' });
  }
})

解决方案2:直接返回相同格式响应(更推荐)

如果不想主动抛错,也可以直接在空值判断分支返回和catch块一致的响应结构,加return终止后续代码执行即可,逻辑更直观:

router.get('/:id', async (req, res) => {
  checkString(req.params.id)
  try {
    const person = await peopleData.getPersonById(req.params.id);
    if(!person) {
      // 直接返回和catch块相同的响应,return避免后续代码执行
      return res.status(404).json({ message: 'There is no person with that ID' });
    }
    res.json(person);
  } catch (e) {
    res.status(404).json({ message: 'There is no person with that ID' });
  }
})

内容的提问来源于stack exchange,提问作者Swayam Shah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:39:01