【问题标题】:How do I display my catch block message when there is no ID match?没有 ID 匹配时,如何显示我的 catch 块消息?
【发布时间】:2021-11-30 16:14:49
【问题描述】:

我正在从 API 获取数据并将其显示在我的本地服务器上。

以下是我从 API 数据中获取与 ID 匹配的数据的代码:

router.get('/:id', async (req, res) => {
  checkString(req.params.id)
  try {
    const person = await peopleData.getPersonById(req.params.id);
    res.json(person);
  } catch (e) {
    res.status(404).json({ message: 'There is no person with that ID' });
  }

如果没有匹配,我想像在 catch 块中一样显示消息,但代码不会去那里,因为从技术上讲,没有匹配不是错误。

所以我尝试了以下代码来获取此消息:

router.get('/:id', async (req, res) => {
  checkString(req.params.id)
  try {
    const person = await peopleData.getPersonById(req.params.id);
    if(!person) res.json('There is no person with that ID'); // Added new line here
    res.json(person);
  } catch (e) {
    res.status(404).json({ message: 'There is no person with that ID' });
  }

这可以工作,但它会将带有引号的消息打印为字符串,如果没有找到匹配项,有没有办法可以在 catch 块中显示消息?

【问题讨论】:

    标签: javascript node.js json express try-catch


    【解决方案1】:

    您正在返回 Json 响应,因此看起来您的消费者不是网页,而是另一个应用程序。如果是这样,如果没有找到人,您应该返回undefinednull,并让网页或消费者决定显示什么消息。原因是:

    1. 修改网页应该比修改代码更容易,通常 UI 或营销人员总是希望微调(通常多次)网页上的每条消息。
    2. 您的应用是 API 应用。显示用户未找到消息的位置可以在许多步之外。或者,显示消息可能完全不合适,例如,如果未找到用户,消费应用可能希望重定向到/显示注册页面。
    3. 您的网站可能是多语言的,您不希望后端参与其中。

    在许多情况下“找不到用户”并不是真正的错误,但这完全取决于您的应用程序。

    在您的情况下,catch 块应该用于处理其他错误,例如,您的数据库服务器可能已关闭,或者数据库请求可能已超时等。您当前的代码将误导性地显示“用户未找到”,如果有数据库错误!

    我也会让 Express 错误处理程序处理这些真正的错误,而不是为您拥有的每个 API 函数编写错误处理代码:

    router.get('/:id', async (req, res, next) => {
      checkString(req.params.id);
      try {
        const person = await peopleData.getPersonById(req.params.id);
        res.json(person); // assuming getPersonById returns null if user not found
      } catch (e) {
        next(e);
    });
    

    您的 Express 错误处理程序(上面的 next 函数所在的位置)应该是这样的(假设 router 是您的 Express 应用程序):

    router.use((err, req, res, next) => {
      let statusCode = err.status || 500;
      // Assuming your app need to return only json responses
      res.json(err);
    });
    

    【讨论】:

      【解决方案2】:

      如果您将人们发送到全屏“错误堆栈”页面,那么您可能不需要使用 res.json()!你也可以使用 res.send()

      if(!person){ res.send('<p>There is no person with that ID</p>'; return; }
      // Or
      if(!person){ res.send('There is no person with that ID'; return; }
      

      【讨论】:

        【解决方案3】:

        你可以抛出一个错误,catch会显示它。

        if(!person) throw new Error("There is no person with that ID");
        
        ....
        
        

        然后在捕获中......

        catch(e){
           res.status(404).json({ message: e.message  })
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-03-08
          • 1970-01-01
          • 2017-03-14
          • 1970-01-01
          • 1970-01-01
          • 2018-08-19
          • 2014-07-06
          • 1970-01-01
          相关资源
          最近更新 更多