In this tutorial, we're going to explore how to handle errors in Express.js, a popular web application framework for Node.js. We will understand how to manage both synchronous and asynchronous errors, which are a common occurrence in web development.
By the end of this tutorial, you will learn:
- The basics of error handling in Express.js
- How to handle synchronous errors
- How to handle asynchronous errors
Prerequisites:
- Basic knowledge of JavaScript
- Understanding of Express.js
- Node.js and NPM installed on your machine
Express.js uses middleware to handle errors. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.
Synchronous errors happen immediately and can be caught directly using a try/catch block.
app.get('/', (req, res) => {
try {
// Some synchronous operation that may throw an error
throw new Error('This is a synchronous error');
} catch (err) {
next(err);
}
});
In the example above, we're throwing an error inside a try/catch block. If an error is thrown, it's caught and passed to the next middleware function using the next function.
Asynchronous errors, on the other hand, cannot be caught directly with a try/catch block because they happen in the future. Instead, we need to pass them to the next function.
app.get('/', (req, res, next) => {
fs.readFile('/some/non/existent/file', (err, data) => {
if (err) {
return next(err); // Pass the error to the next middleware function
}
res.send(data);
});
});
In this example, we're trying to read a file that doesn't exist. When an error occurs, it's passed to the next middleware function.
Let's see how to create a middleware function to handle these errors.
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log error stack to console
res.status(500).send('Something broke!'); // Send error message to client
});
This error-handling middleware function takes four arguments instead of the usual three. This is how Express.js identifies error-handling middleware functions.
In this tutorial, we've learned how to handle both synchronous and asynchronous errors in Express.js. We've also seen how to create a middleware function to handle these errors.
To practice and improve your skills, try creating different error scenarios and handle them using the techniques discussed in this tutorial.
Some additional resources you might find helpful include:
- Express.js Error Handling
- Error Handling in Node.js
Solutions:
1.
app.get('/parse', (req, res, next) => {
try {
JSON.parse('Invalid JSON string');
} catch (err) {
next(err);
}
});
app.get('/read', (req, res, next) => {
// Simulate reading from a database
database.read('non-existent', (err, data) => {
if (err) {
return next(err);
}
res.send(data);
});
});
Remember to practice the concepts you've learned in this tutorial to fully understand error handling in Express.js. Happy coding!