Error handling is a crucial aspect of any application, and Express.js provides several mechanisms to handle errors effectively. In this section, we will cover:
- Understanding Error Handling in Express
- Creating Error Handlers
- Using Built-in Error Handlers
- Custom Error Handling Middleware
- Practical Examples
- Exercises
- Understanding Error Handling in Express
In Express, error handling is done using middleware. 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. Error-handling middleware functions have four arguments instead of three: (err, req, res, next)
.
- Creating Error Handlers
To create an error handler in Express, you define a middleware function with four arguments. Here’s a basic example:
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });
In this example:
err
is the error object.req
is the request object.res
is the response object.next
is the next middleware function.
- Using Built-in Error Handlers
Express comes with a built-in error handler that handles any errors passed to next(err)
. If you do not define your own error-handling middleware, Express will use its default error handler.
- Custom Error Handling Middleware
You can create custom error-handling middleware to handle specific types of errors or to provide more detailed error messages. Here’s an example of custom error-handling middleware:
// Custom error handler for 404 - Not Found app.use((req, res, next) => { res.status(404).send('Sorry, we could not find that!'); }); // Custom error handler for other errors app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something went wrong!'); });
In this example:
- The first middleware handles 404 errors.
- The second middleware handles all other errors.
- Practical Examples
Example 1: Handling 404 Errors
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); // 404 Error Handler app.use((req, res, next) => { res.status(404).send('Sorry, we could not find that!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
Example 2: Handling Other Errors
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); // Simulate an error app.get('/error', (req, res, next) => { const err = new Error('Something went wrong!'); next(err); }); // Error Handler app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something went wrong!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
- Exercises
Exercise 1: Create a Custom Error Handler
Task: Create an Express application with a custom error handler that handles 404 errors and other errors separately.
Solution:
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); // 404 Error Handler app.use((req, res, next) => { res.status(404).send('Sorry, we could not find that!'); }); // General Error Handler app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something went wrong!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
Exercise 2: Simulate and Handle an Error
Task: Modify the previous application to simulate an error when accessing the /error
route and handle it using the custom error handler.
Solution:
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); // Simulate an error app.get('/error', (req, res, next) => { const err = new Error('Something went wrong!'); next(err); }); // 404 Error Handler app.use((req, res, next) => { res.status(404).send('Sorry, we could not find that!'); }); // General Error Handler app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something went wrong!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
Conclusion
In this section, we covered the basics of error handling in Express.js. We learned how to create custom error-handling middleware, use built-in error handlers, and handle specific types of errors. Error handling is essential for building robust applications, and mastering it will help you create more reliable and maintainable code.
Next, we will move on to Module 7, where we will explore databases and ORMs, starting with an introduction to databases.
Node.js Course
Module 1: Introduction to Node.js
Module 2: Core Concepts
Module 3: File System and I/O
Module 4: HTTP and Web Servers
Module 5: NPM and Package Management
- Introduction to NPM
- Installing and Using Packages
- Creating and Publishing Packages
- Semantic Versioning
Module 6: Express.js Framework
- Introduction to Express.js
- Setting Up an Express Application
- Middleware
- Routing in Express
- Error Handling
Module 7: Databases and ORMs
- Introduction to Databases
- Using MongoDB with Mongoose
- Using SQL Databases with Sequelize
- CRUD Operations
Module 8: Authentication and Authorization
Module 9: Testing and Debugging
- Introduction to Testing
- Unit Testing with Mocha and Chai
- Integration Testing
- Debugging Node.js Applications
Module 10: Advanced Topics
Module 11: Deployment and DevOps
- Environment Variables
- Using PM2 for Process Management
- Deploying to Heroku
- Continuous Integration and Deployment