首页 > 解决方案 > 在强大的 form.parse 中, throw 关键字无法正常工作

问题描述

使用 throw 关键字,每次我点击路径时它都不起作用,总是给我指向单词 throw 关键字的错误,如果我删除 throw 它的工作检查代码以供参考,我在 server.js 中有我的自定义错误处理程序,它与其他导出工作正常

exports.createMainCategory = asyncHandler(async (req, res) => {
      let form = new formidable.IncomingForm();
      form.keepExtensions = true;
    
      form.parse(req, (err, fields, file) => {
        if (err) {
          res.status(400);
          throw new Error("problem with image");
        }
        const { maincategory } = fields;
    
        if (!maincategory) {
          //NOT WORKING WITH THIS
    
          res.status(400);
          throw new Error("include all files");
    
          // ONLY WORKIN WITH BELOW CODE
    
          // return res.status(400).json({
          //   error: "Please include all fields",
          // });
        }
    
        let mainCat = new MainCat(fields);
    
        //handle file here
        if (file.photo) {
          if (file.photo.size > 3000000) {
            res.status(400);
            throw new Error("File size too big!");
          }
          mainCat.photo.data = fs.readFileSync(file.photo.path);
          mainCat.photo.contentType = file.photo.type;
        }
    
        //save to the DB
    
        mainCat.save((err, mcategory) => {
          if (err) {
            res.status(400).json({
              error: "Saving category in DB failed",
            });
          }
          res.json(mcategory);
        });
      });
    });

标签: javascriptnode.jsexpressformidable

解决方案


推荐阅读