Multer handle error, problem with typescript types

Viewed 595

I have the following code:

import multer from "multer";
const upload = multer().single('file');
router.post('/add', async (req, res) => {
    upload(req, res, async (err: any) => {
        if (err) {
            res.status(500).send(err.toString())
        }
        else {
            res.status(200).send(await addMedia(req.file.filename))
        }
    })
});

I am trying to determine the type, so I want to replace any by an appropriate Error type. When I try to replace it with MulterError, I get following error :

Argument of type '(err: MulterError) => Promise' is not assignable to parameter of type 'NextFunction'. Types of parameters 'err' and 'deferToNext' are incompatible. Type 'string' is not assignable to type 'MulterError'.

unknown does not work due to the .toString(). string does work, but it is definitely not the correct type, as logging it shows me that I have a MulterError.

I don't completely understand what the 3rd parameter of the upload function is either - so that may be my issue.

1 Answers

This is how I handled error

const storage: multer.StorageEngine = multer.diskStorage({
    destination: (_req, _file, callback) => {
        const path = `./uploads/`;
        // creates folder if not exist
        fs.mkdirSync(path, { recursive: true });
        callback(null, path);
    },
    filename: (_req, file, callback) => {
        callback(null, new Date().toISOString() + file.originalname);
    }
});

const fileLimit = {
    fileSize: 1024 * 1024 * 10 // limits the file size to 10MB
};
const fileFilter = (
    _req: Request,
    file: Express.Multer.File,
    callback: FileFilterCallback
) => {
    // return error if the file type is not image
    if (!file || file.mimetype.split('/')[0] != 'image') {
        return callback(new Error('Only images allowed'));
    }
    callback(null, true);
};

const upload: multer.Multer = multer({
    storage: storage,
    limits: fileLimit,
    fileFilter: fileFilter
});

const galleryUpload = upload.single('galleryImage');
// Upload gallery image
router.post('/', async (req: Request, res: Response) => {
    galleryUpload(req, res, (err: unknown) => {
        if (err instanceof multer.MulterError) {
            // A Multer error occurred when uploading.
            return res.status(400).send({ message: err.message });
        } else if (err instanceof Error) {
            // An unknown error occurred when uploading.
            return res.status(400).send({ message: err.message });
        }
        return res.status(200).send({ message: 'Image uploaded successfully' });
    });
});
Related