【问题标题】:catching thrown errors from callback function javascript从回调函数javascript捕获抛出的错误
【发布时间】:2021-09-30 14:23:27
【问题描述】:

我正在 try-catch 中运行一些函数。我正在使用 fs.unlink 根据要求删除一些文件。但如果没有这样的文件,我想抛出一个错误。但我无法捕捉到错误。它总是导致应用程序崩溃

这是我的代码:

  app.delete("/product", (req, res) => {
    const id = req.body.id;

    try {
      Product.findByPk(id)
        .then((product) => {
          if(product) {
            const images = JSON.parse(product.image);

            for(let i = 0; i < images.length; i++) {
              fs.unlink(`public/images/${images[i]}`, (err) => {
                if (err) throw new Error(err);
              });
            }
    
            product.destroy();
          }else {
            res.status(404).json({ msg: "can't delete product with id: " + id + ". It doesn't exist in database."});
          }
        });
      res.status(200).json({ msg: "Deleted product with id: " + id });
    } catch (error) {      
      res.status(500).json({ msg: "An error with code 'NW_DELETE_1' occured." });
      Log.error("ERROR is this: " + error);
    }

  });

Product.finByPk 来自Sequelize

Log 对象来自bunyan logger。

你能告诉我如何处理这段代码中所有可能的错误吗? 我不想捕获错误并使用 Log 将其记录到控制台。我不想避免在 fs.unlink 上删除不存在的文件等程序员错误。

我是编程新手。请注意您发现的任何错误。

【问题讨论】:

  • 而不是使用 throw error use-console.log(err)。抛出错误会使您的应用崩溃
  • 我知道如何记录错误。但我想抓住它。我想防止应用崩溃
  • 您正在使用if (err) throw new Error(err); 捕获它,但您在同一行中再次抛出错误。如果您不想让它崩溃并记录它,您可以将该行替换为:if (err) Log.error("ERROR is this: " + error);
  • 我认为你是对的。我不需要在这里抛出任何错误。谢谢。

标签: node.js error-handling callback fs


【解决方案1】:

在这种情况下,try-catch 无法捕获异常,因为您的代码在 .then() 处理程序中异步执行。

您需要添加一个.catch() 处理程序:

  app.delete("/product", (req, res) => {
    const id = req.body.id;

    Product.findByPk(id)
      .then((product) => {
        if (product) {
          const images = JSON.parse(product.image);

          for (let i = 0; i < images.length; i++) {
            fs.unlink(`public/images/${images[i]}`, (err) => {
              if (err) throw new Error(err);
            });
          }
  
          product.destroy();
          res.status(200).json({ msg: "Deleted product with id: " + id });
        } else {
          res.status(404).json({ msg: "can't delete product with id: " + id + ". It doesn't exist in database."});
        }
      })
      .catch((error) => {
        res.status(500).json({ msg: "An error with code 'NW_DELETE_1' occured." });
        Log.error("ERROR is this: " + error);   
      });
  });

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 2015-06-29
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2015-12-06
    • 2017-10-23
    相关资源
    最近更新 更多