In this tutorial, we'll learn how to handle errors effectively while uploading files using Multer and Express.js. We'll explore the various types of errors that can occur during file uploads and how to respond to them appropriately in your application.
By the end of this tutorial, you'll be able to:
Prerequisites: Basic knowledge of JavaScript, Express.js, and Node.js is recommended.
Multer is a popular middleware for Express and Node.js that enables handling multipart/form-data, primarily used for uploading files. It's flexible and easy to use but can throw errors when things don't go as planned.
Let's learn how to handle these errors effectively:
LIMIT_PART_COUNT
, LIMIT_FILE_SIZE
, LIMIT_FILE_COUNT
, LIMIT_FIELD_KEY
, LIMIT_FIELD_VALUE
, LIMIT_FIELD_COUNT
, LIMIT_UNEXPECTED_FILE
.Understanding these error types can help you handle them appropriately.
app.use()
and routes calls to catch any errors thrown.Let's look at a code example of a basic file upload system with Multer and Express.js, and how to handle errors:
const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer({
dest: 'uploads/',
limits: { fileSize: 1000000 }, // restricts file size to 1MB
});
app.post('/upload', upload.single('myFile'), (req, res) => {
res.send('File uploaded successfully.');
}, (error, req, res, next) => {
// This is the error handling middleware
res.status(400).send({ error: error.message }); // sends the error message as response
});
app.listen(3000, () => console.log('Server started on port 3000'));
In this code example, we define multer with a limit of 1MB for file size. If a larger file is uploaded, multer will throw a LIMIT_FILE_SIZE
error, which our error handling middleware will catch and send a response to the client.
In this tutorial, we've learned how to handle errors in file uploads using Multer and Express.js, understanding different types of errors, and how to define an error handling middleware in Express.js.
For further learning, you can explore different error types thrown by Multer and how to handle each of them. You can also learn about different storage engine options available in Multer.
multer
's fileFilter
option.{ error: 'Only image files are allowed.' }
Here's a solution for the above exercises:
const upload = multer({
dest: 'uploads/',
limits: { fileSize: 1000000 },
fileFilter: (req, file, cb) => {
if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
return cb(new Error('Only image files are allowed.'));
}
cb(null, true);
}
});
In this code, we have added a fileFilter
function in our multer configuration. This function checks if the uploaded file is an image (jpg, jpeg, or png). If not, it throws an error, which our error handling middleware will catch and send a response to the client.