在什么情况下可能 res.status() 或 res.json() 抛出/引发错误

问题描述 投票:0回答:1

我有一个库的通用函数:

const sendResponse = (res: Response, type: HavenErrorType, errorTrace: InspectedError) => {

  if (res.headersSent) {
    log.warning('Warning: headers already sent for response. Error:', errorTrace);
  }

  try {
    res.status(500);  // this one
  } catch (err) {
    log.error(err);
  }

  try {
    res.json({   // this one
      foo: 'bar'
    });

  } catch (err) {
    log.error(err);
  }

};

我很好奇 res.status() 和 res.json() 可能会引发哪些类型的错误 - 最好的选择是查看源代码还是有更好的方法来找出答案?

javascript node.js http httpresponse
1个回答
1
投票

我能想到的一些情况:

  1. res
    无效,要么不是对象,要么没有
    status
    json
    方法。
  2. 如果您给它一个无效的参数或给它一个包含循环引用的对象(无法用 JSON 表示),
  3. res.json()
    可能会失败。

此外,您应该知道

res.status(500)
不会发送响应。这只是将状态代码设置为 500,以便稍后调用类似
res.end()
之类的内容时,这将是状态代码。也许您想使用
res.sendStatus(500)
。这将设置状态并发送响应。

并且请注意,您可以使用一个

try/catch
来涵盖这两种方法调用。您不需要为每个单独的
try/catch
块。

© www.soinside.com 2019 - 2024. All rights reserved.