Node.js / Node.js Express Framework
Error Handling and Middleware in Express
This tutorial covers error handling in Express and the concept of middleware chaining. You'll learn how to catch and handle errors, and how to pass control between middleware func…
Section overview
5 resourcesCovers building web applications and REST APIs using the Express framework.
Tutorial: Error Handling and Middleware in Express.js
1. Introduction
In this tutorial, we aim to explore error handling and middleware in Express.js. Express.js is a fast, unopinionated, and minimalist web application framework for Node.js.
By the end of this tutorial, you will:
- Understand how middleware works in Express.js
- Learn how to handle errors in Express.js
- Be able to develop middleware functions and use them for error handling
The prerequisites for this tutorial are a basic understanding of JavaScript and some familiarity with Node.js and Express.js.
2. Step-by-Step Guide
Understanding 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. The next middleware function is commonly denoted by a variable named next.
Middleware functions can perform the following tasks:
- Execute any code
- Make changes to the request and the response objects
- End the request-response cycle
- Call the next middleware function in the stack
Error Handling in Express
In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. To handle a 404 response, add a middleware function at the end of the stack.
Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it.
3. Code Examples
Basic Error Handling
app.use(function(err, req, res, next) {
console.error(err.stack); // Log error message in our server's console
res.status(500); // Announce that this is a 500 error
res.send('Something broke!'); // Inform client about the error
});
In this example, app.use is used to setup middleware. We're passing a function that accepts four arguments to app.use. This function is an error handling middleware. Express identifies it as such and passes errors to it.
404 Handling
app.use(function(req, res, next) {
res.status(404).send('Sorry cant find that!');
});
This middleware function does not have an error in its arguments, Express treats it as a regular middleware. You should ensure this comes after all your other routes because responses are sent in order.
4. Summary
In this tutorial, we have learned about error handling and middleware in Express.js. We've seen how Express uses middleware and how to create error handling middleware.
For further learning, consider exploring more about Express middleware, like built-in middleware, third-party middleware, and writing your own middleware functions.
5. Practice Exercises
- Create a middleware function that logs the current date and time each time a request is made to the server.
- Create an error handling middleware that responds with a custom error page.
- Create a middleware stack with at least three middleware functions, where each function logs something to the console and passes control to the next middleware function.
Tips: Always handle errors and be prepared for the unexpected. Remember, middleware functions that do not handle errors must take only three parameters. Otherwise, they might be mistaken for error handling functions.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article