Selected topic
Error Handling
Prefer practical output? Use related tools below while reading.
=====================================
In Express.js, error middleware is used to handle errors that occur during the execution of routes. It's a crucial part of building robust and reliable web applications.
The primary goal of error middleware is to catch and handle unexpected errors that might not be anticipated by developers. This ensures that your application remains stable and doesn't crash when an error occurs.
javascript
const express = require('express');
const app = express();app.use((err, req, res, next) => {
console.error(err); // Log the error for debugging purposes
res.status(500).send({ message: 'Internal Server Error' });
});
// Example route that might throw an error
app.get('/users', (req, res) => {
// Simulating an error by trying to access a non-existent property
const user = req.body.user;
if (!user) {
throw new Error('User not found');
}
res.json(user);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
In this example:
next function is not called in this middleware, as we're handling the error ourselves./users that might throw an error if the user property is missing from the request body.next(): When handling an error in middleware, don't call the next() function, as this will propagate the error to the next middleware or route handler.