Express default error handler not sending response

44 Views Asked by At

I am uloading image using multer and then compressing image using gm. While uploading image, I am checking for file type and if its not image, throwing err to global err handler for skipping image compression. Thrown err is handled by global err handler but cant send response to frontend from the handler. Tried all resources but nothing seems working!

Routing:

router.post(
  "/updateProfile",
  auth,
  upload(uploadUser.single("file")),
  compressImages,
  (req, res) => {}

Upload middleware:

const imageFilter = (req, file, cb) => {
  const allowedExtensions = /(jpg|jpeg|png)$/i;
  const allowedMimetypes = /(image\/jpeg|image\/png)$/i;

  if (
    allowedExtensions.test(path.extname(file.originalname)) &&
    allowedMimetypes.test(file.mimetype)
  ) {
    cb(null, true);
  } else {
    cb(new CustomError("Invalid file type, only .jpeg/.png allowed!", 415));
  }
};

const upload = (uploadType) => (req, res, next) => {
  uploadType(req, res, (err) => {
    if (err) {
      return next(err);
    }
    return next();
  });
};

Global err handler:

const errorHandler = (err, req, res, next) => {
  if (res.headersSent) {
    console.log("headers sent");
    return next(err);
  }
  if (err) {
    res.setHeader("Content-Type", "application/json");
    return res
      .status(err.statusCode || 500)
      .json(new ApiResponse(err.message || "Something went wrong!", null));
  }
  return next(err);
};
app.use(errorHandler);
1

There are 1 best solutions below

0
On

In errorHandler, send a respone only if err exists, let it wrap around the rest:

const errorHandler = (err, req, res, next) => {
  if (err) {
    if (res.headersSent) {
      console.log("headers sent");
      return next(err);
    }
    res.setHeader("Content-Type", "application/json");
    return res
      .status(err.statusCode || 500)
      .json(new ApiResponse(err.message || "RRR, something went wrong!", null));
  }
  return next(err);
};