How to Catch and Handle Multer Errors to Prevent Node.js Program from Crashing?

41 views Asked by At

I'm using Multer for file uploads in my koa application. When the uploaded file does not meet the specified mimetype or size limit, Multer throws a MulterError, which causes my program to crash. I've tried using async/await, promise.catch(), and app.on("error") to catch these errors, but none seem to work effectively.

const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
    cb(null, true); 
  } else {
    cb(new Error('The file format is incorrect!'), false);
  }
};
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const targetDir = `${uploadPath}`;
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true });
    }
    cb(null, targetDir);
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${file.originalname}`);
  },
});
const upload = multer({
  storage,
  limits: {
    fileSize: 200,
  },
  fileFilter
}).single("avatar");
const uploadHandle = async (ctx, next) => {
return new Promise((resolve, reject) => {
  upload(ctx, (err) => {
    if (err) {
      reject(err);
      return ctx.app.emit("error", err, ctx);
     } else {
         resolve(ctx.file);
       }
  });
 })
}```
0

There are 0 answers