从回调函数javascript中捕获抛出的错误

时间:2021-07-23 12:50:51

标签: node.js error-handling callback fs

我正在 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 记录器。

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

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

1 个答案:

答案 0 :(得分:0)

在这种情况下,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);   
      });
  });
相关问题