In Express.js, error handling can be done using middleware functions. When an error occurs in your application, Express.js will pass the error object to the next error-handling middleware function. Here’s an example of how you can implement error handling in Express.js.
error-handling middleware
Let’s create an error-handling middleware function.
app.use((err, req, res, next) => {
// Default status code to 500 if it's not set
const statusCode = res.statusCode !== 200 ? res.statusCode : 500;
// Set the status code and send the error message
res.status(statusCode).json({
message: err.message,
stack: process.env.NODE_ENV === 'production' ? '' : err.stack
});
});
How to use the error-handling middleware function
Use the error-handling middleware function in your application
// Define your routes and middleware functions
app.get('/', (req, res, next) => {
// Example error, assuming `someFunction` throws an error
try {
someFunction();
} catch (err) {
next(err); // Pass the error to the error-handling middleware
}
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, when an error occurs in the route handler (/
), the next(err)
statement is called to pass the error object to the error-handling middleware. The middleware function then sets the appropriate status code and sends a JSON response with the error message.
It’s important to define the error-handling middleware after all other routes and middleware functions in your application, as Express.js will sequentially pass the error to the next error-handling middleware function if one exists.
Remember to replace someFunction()
with your actual code that might throw an error. You can customize the error-handling middleware to suit your needs, such as logging the error or providing additional error details based on your application’s requirements.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.