In this tutorial, we will explore how to effectively handle errors and validate data in an Express.js and MongoDB application. Proper error handling and data validation are key components in building robust and secure applications. By the end of this tutorial, you will learn:
Prerequisites: Basic understanding of JavaScript, Node.js, Express.js, and MongoDB. Familiarity with Mongoose would be beneficial but not necessary.
Express.js has a built-in error handler that takes care of any unhandled errors that might occur in your application. However, for custom error handling, you can define your own middleware function.
app.use((err, req, res, next) => {
console.error(err.stack); // logs error stack trace to console
res.status(500).send('Something broke!');
});
In this example, we define a middleware function that logs the error stack trace to the console and sends a response with status code 500 and a custom error message.
Mongoose provides several built-in validators, as well as custom validation. For example, to ensure a field is required or to validate the length of a string.
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
}
});
In this example, we define a schema for user where the name is required and must be between 5 and 50 characters.
app.get('/', (req, res, next) => {
fs.readFile('/file-does-not-exist', (err, data) => {
if (err) {
next(err); // Passes the error to the error handler
} else {
res.send(data);
}
});
});
In this example, we try to read a file that does not exist. If an error occurs (which it will), we pass the error to the next function, which is the error handler.
let User = mongoose.model('User', userSchema);
let user = new User({ name: 'John' });
user.save((err) => {
if (err) console.log('Error:', err);
else console.log('User saved successfully');
});
In this example, we try to save a user with a name that is less than 5 characters. Because our schema specifies a minimum length of 5, Mongoose will throw a validation error.
In this tutorial, we have covered how to handle errors in Express.js, validate data with Mongoose, and the importance of these practices for the robustness and security of your application.
For further learning, consider exploring more advanced error handling techniques and other validation libraries for Node.js like Joi and express-validator.
Solution:
javascript
app.get('/', (req, res, next) => {
fs.readFile('/file-name', (err, data) => {
if (err) {
next(err);
} else {
res.send(data);
}
});
});
Solution:
javascript
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
validate: {
validator: function(v) {
// regex to validate email format
return /^([\w-]+@([\w-]+\.)+[\w-]{2,4})?$/.test(v);
},
message: props => `${props.value} is not a valid email!`
}
},
password: {
type: String,
required: true,
minlength: 8
}
});
Remember to practice and try to understand each concept thoroughly. Good luck!