Search code examples
node.jsexpressfile-uploaderror-handlingmulter

Return statusCode with message in fileFilter multer


I want to make a filter for uploaded files using multer package, and my validation works.

But I want when user send wrong files, I return statusCode and message together.

NOTE: I can send message or send statusCode but I want send both.

here is my code

import { v4 as uuidv4 } from "uuid"
import multer from "multer";

const AVAILABLE_IMAGE_FORMATS = ["image/jpg", "image/jpeg", "image/png", "image/gif"]
const __dir_images__ = `${__dirname__}/../uploads/images`

class HandledRespError {
  constructor(statusCode = 500, message = Messages.failed) {
    return {
      statusCode: statusCode,
      message: message
    }
  }
}

const multerStorageFileName = function(req, file, cb) {
  const uniqueName = uuidv4() + "--" + file.originalname
  return cb(null, uniqueName)
}

const imageStorage = multer.diskStorage({
  destination: __dir_images__,
  filename: multerStorageFileName
});

const imageFileFilter = function(req, file, cb) {
  if ( ! AVAILABLE_IMAGE_FORMATS.includes(file.mimetype) ) return cb(new HandledRespError(406), false) // I think my problem is here

  cb(null, true)
}

export const imageUpload = multer({storage: imageStorage, fileFilter: imageFileFilter})

if I use return cb( "my message", false) or return cb( new Error("my message"), false) it will return my message with statusCode 500.

if I send return cb({statusCode:406, message: "my message"}, false) or return cb({status:406, message: "my message"}, false), it will return statusCode 406 and message will be [object object]

how can I handle both statusCode and message together?

this is postman response

UPDATE:

I use const exeption = new Error("Operation Failed!"); exeption.statusCode = 406. It worked but I got some other messages and I don't want these messages.

result of new code:

enter image description here

And one more thing, how can I change html response to JSON response?


Solution

  • Set the statusCode property on the error object rather than passing it as a parameter:

    var err = new Error("error 406");
    err.statusCode = 406;
    return cb(err);
    

    How this error is ultimately presented to the client depends on the express error handler. See the linked documentation for how the standard error handler behaves and how you can write you own.