Explain Error Handling in Express.js Using An Example
Last Updated :
23 Jul, 2025
Error Handling is one of the most important parts of any web application development process. It ensures that when something goes wrong in your application, the error is caught, processed, and appropriately communicated to the user without causing the app to crash. In Express.js error handling, requires a proper understanding of how middleware and error-handling mechanisms work.
What is Error Handling in Express.js?
Error Handling in Express.js involves capturing and managing errors that occur during the processing of HTTP requests. This may involve validation errors, runtime errors, database connection issues, or other unexpected exceptions. Without proper error handling, these errors can lead to unhandled rejections, server crashes, or poor user experiences.
Express uses a middleware approach to handle errors, allowing you to define functions that catch and respond to errors throughout your application.
How Error Handling Works in Express.js?
Express.js handles errors through middleware functions, specifically error-handling middleware. A middleware in Express is a function that takes in a request (req), response (res), and the next function (next). In the case of error-handling middleware, it also takes in an additional err argument, making it look like this:
function errorHandler(err, req, res, next) {
// Handle the error
}
For Express to recognize a middleware as an error handler, it must have four parameters: err, req, res, and next. This middleware can be placed at any point in the request-response cycle but is often placed after route definitions to catch errors generated during request processing.
Reason For Using Error Handling in Express.js
- To prevent application crashes: Without error handling, unhandled errors can cause an application to crash, leading to poor user experience and potential data loss. Error handling allows you to capture and respond to errors, preventing them from causing a crash and keeping the application running smoothly.
- To provide meaningful error messages: Error handling allows you to provide meaningful and user-friendly error messages to your users, rather than leaving them with a blank screen or a default error message. This can help to improve the overall user experience and prevent confusion or frustration.
- To improve debugging: Error handling allows you to capture and log errors, making it easier to debug your application and identify the root cause of any issues. This can save time and effort when troubleshooting problems with your application.
- To comply with standards and regulations: Proper error handling is often a requirement for compliance with security standards and regulations. By handling errors correctly, you can ensure that your application meets these standards and regulations.
Ways to Perform Error Handling
Express.js has built-in support for error-handling middleware, which allows you to handle errors that occur during the execution of the application.
Syntax:
app.use(function(error, request, response, next) {
// Handle the error
response.status(500).send('Internal Server Error');
});
2. Try-Catch statements
You can use try-catch statements to handle errors that occur within specific blocks of code. This ensures that any errors that occur are caught and handled in a controlled manner.
Syntax:
app.get('/', function (req, res) {
try {
// Code that might throw an error
} catch (error) {
// Handle the error
res.status(500).send('Internal Server Error');
}
});
3. Error logging
You can set up error logging so that any errors that occur during the execution of the application are logged to a file or a database for later analysis.
Syntax:
app.get('/', function (req, res) {
try {
throw new Error('Something went wrong');
} catch (error) {
console.error(error);
}
});
Error codes: You can set up error codes for different types of errors that occur during the execution of the application. This makes it easier to identify and handle specific errors.
- Error codes in Node.js are symbolic values that represent specific types of errors that can occur during the execution of a program.
- For example, the Node.js fs module uses error codes such as 'ENOENT' (no such file or directory) or 'EACCES' (permission denied) to represent specific types of file system errors.
- When an error occurs in your Node.js application, you can access the error code by checking the code property of the error object.
Example:
const fs = require('fs');
fs.readFile('nonexistent-file.txt', (error, data) => {
if (error) {
console.error(error.code);
} else {
console.log(data.toString());
}
});
You can use HTTP status codes to indicate the type of error that occurred. For example, a status code of 400 (Bad Request) can indicate a validation error, while a status code of 500 (Internal Server Error) can indicate a server-side error.
Syntax:
const http = require('http');
const server = http.createServer((request, response) => {
response.statusCode = 200;
response.end('OK');
});
server.listen(8080);
- By using any of the above, you can handle errors in a controlled and efficient manner, and ensure that your application is robust and stable.
Let's see some basic examples and explanations for Error Handling in Express.js:
Example 1: Using a middleware function: You can use a middleware function to handle errors that occur during the execution of an application. The middleware function should have four arguments: error, request, response, and next.
JavaScript
const express = require('express');
const app = express();
// Custom error handling middleware
const errorHandler = (err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
};
app.use((req, res, next) => {
throw new Error('Something broke!');
});
// Use the custom error handling middleware
app.use(errorHandler);
app.listen(3000, () => {
console.log('App is listening on port 3000');
});
Steps to run the application: Write the below code in the terminal to run the application:
node index.js
Output:
Explanation:
- In this example, we define a custom error-handling middleware function errorhandler that logs the error stack and sends a response with a status code of 500 and the message "Something went wrong!".
- We then use the custom error handling middleware by adding the app.use(errorhandler) after defining it.
- This error-handling middleware will catch any errors thrown in the previous middleware or routes, and handle them according to the logic defined in the errorHandler function.
- The first line App is listening on port 3000 is logged when the Express app starts listening on port 3000.
- If you make a request to the app, the custom middleware will throw an error, which will then be caught by the error-handling middleware. The error stack trace will be logged to the console, and the response sent to the client will have a status code of 500 and the message "Something went wrong!".
Example 2: Using the try-catch statement: You can use the try-catch statement to handle errors that occur within a specific block of code.
JavaScript
const express = require('express');
const app = express();
app.get('/', (req, res, next) => {
try {
// Some code that might throw an error
const data = someFunctionThatMightThrowError();
res.status(200).json(
{ message: 'Data retrieved successfully', data });
} catch (error) {
next(error);
}
});
// Custom error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json(
{ message: 'Something went wrong!' });
});
app.listen(3000, () => {
console.log('App is listening on port 3000');
});
Explanation:
- In this example, we wrap the code that might throw an error in a try block. If an error is thrown, it will be caught by the corresponding catch block, which logs the error stack and sends a response with a status code of 500 and the message "Something went wrong!".
- This approach allows for more fine-grained error handling, as the try-catch statement can be used multiple times in different middleware functions or routes.
Steps to run the application: Write the below code in the terminal to run the application:
node index.js
Output:
Explanation:
- If you make a request to the app, the custom middleware will throw an error, which will then be caught by the try-catch statement. The error stack trace will be logged to the console, and the response sent to the client will have a status code of 500 and the message "Something went wrong!".
- Note that the [ERROR STACK TRACE] part of the output will vary depending on the exact error that was thrown. It will contain details about the error, such as the error message and the location in the code where the error was thrown.
- his output will be displayed if you make a request to the app and an error is thrown by the custom middleware. The error stack trace will be logged to the console and the response sent to the client will have a status code of 500 and the message "Something went wrong!".
- This output will be displayed when the Express app starts listening on port 3000. No error will be thrown if you do not make any requests to the app.
Example 3: Using the next() function: You can use the next() function to pass errors to the next middleware function in the chain.
JavaScript
const express = require('express');
const app = express();
app.get('/', (req, res, next) => {
// Some code that might throw an error
const data = someFunctionThatMightThrowError();
if (!data) {
return next(new Error('Error retrieving data'));
}
res.status(200).json(
{ message: 'Data retrieved successfully', data });
});
// Custom error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json(
{ message: 'Something went wrong!' });
});
app.listen(3000, () => {
console.log('App is listening on port 3000');
});
Explanation:
- In this example, we have two middleware functions. The first middleware function throws an error, and the second middleware function is used for error handling. If an error is thrown in the first middleware function, the control flow is passed to the second middleware function using the next() function. The error is then logged to the console and a response with a status code of 500 and the message "Something went wrong!" is sent to the client.
- This approach allows for error handling to be handled separately from the middleware functions that perform the core functionality of the application.
Steps to run the application: Write the below code in the terminal to run the application:
node index.js
Here's an example using curl:
- Open a terminal or command prompt.
- Navigate to the directory where the program is located.
- Start the application by running node app.js.
- In another terminal window, run the following command to make a request to the '/' endpoint:
curl http://localhost:3000
Output:
- If you make a request to the app, the first middleware function will throw an error. The error will be passed to the second middleware function using the next() function, where it will be logged to the console and a response with a status code of 500 and the message "Something went wrong!" will be sent to the client.
- Note that the [ERROR STACK TRACE] part of the output will vary depending on the exact error that was thrown. It will contain details about the error, such as the error message and the location in the code where the error was thrown.
Similar Reads
Node.js Tutorial Node.js is a powerful, open-source, and cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript code outside the browser, making it ideal for building scalable server-side and networking applications.JavaScript was mainly used for frontend developme
4 min read
Introduction & Installation
NodeJS IntroductionNodeJS is a runtime environment for executing JavaScript outside the browser, built on the V8 JavaScript engine. It enables server-side development, supports asynchronous, event-driven programming, and efficiently handles scalable network applications. NodeJS is single-threaded, utilizing an event l
5 min read
Node.js Roadmap: A Complete GuideNode.js has become one of the most popular technologies for building modern web applications. It allows developers to use JavaScript on the server side, making it easy to create fast, scalable, and efficient applications. Whether you want to build APIs, real-time applications, or full-stack web apps
6 min read
How to Install Node.js on LinuxInstalling Node.js on a Linux-based operating system can vary slightly depending on your distribution. This guide will walk you through various methods to install Node.js and npm (Node Package Manager) on Linux, whether using Ubuntu, Debian, or other distributions.PrerequisitesA Linux System: such a
6 min read
How to Install Node.js on WindowsInstalling Node.js on Windows is a straightforward process, but it's essential to follow the right steps to ensure smooth setup and proper functioning of Node Package Manager (NPM), which is crucial for managing dependencies and packages. This guide will walk you through the official site, NVM, Wind
6 min read
How to Install NodeJS on MacOSNode.js is a popular JavaScript runtime used for building server-side applications. Itâs cross-platform and works seamlessly on macOS, Windows, and Linux systems. In this article, we'll guide you through the process of installing Node.js on your macOS system.What is Node.jsNode.js is an open-source,
6 min read
Node.js vs Browser - Top Differences That Every Developer Should KnowNode.js and Web browsers are two different but interrelated technologies in web development. JavaScript is executed in both the environment, node.js, and browser but for different use cases. Since JavaScript is the common Programming language in both, it is a huge advantage for developers to code bo
6 min read
NodeJS REPL (READ, EVAL, PRINT, LOOP)NodeJS REPL (Read-Eval-Print Loop) is an interactive shell that allows you to execute JavaScript code line-by-line and see immediate results. This tool is extremely useful for quick testing, debugging, and learning, providing a sandbox where you can experiment with JavaScript code in a NodeJS enviro
5 min read
Explain V8 engine in Node.jsThe V8 engine is one of the core components of Node.js, and understanding its role and how it works can significantly improve your understanding of how Node.js executes JavaScript code. In this article, we will discuss the V8 engineâs importance and its working in the context of Node.js.What is a V8
7 min read
Node.js Web Application ArchitectureNode.js is a JavaScript-based platform mainly used to create I/O-intensive web applications such as chat apps, multimedia streaming sites, etc. It is built on Google Chromeâs V8 JavaScript engine. Web ApplicationsA web application is software that runs on a server and is rendered by a client browser
3 min read
NodeJS Event LoopThe event loop in Node.js is a mechanism that allows asynchronous tasks to be handled efficiently without blocking the execution of other operations. It:Executes JavaScript synchronously first and then processes asynchronous operations.Delegates heavy tasks like I/O operations, timers, and network r
5 min read
Node.js Modules , Buffer & Streams
NodeJS ModulesIn NodeJS, modules play an important role in organizing, structuring, and reusing code efficiently. A module is a self-contained block of code that can be exported and imported into different parts of an application. This modular approach helps developers manage large projects, making them more scal
6 min read
What are Buffers in Node.js ?Buffers are an essential concept in Node.js, especially when working with binary data streams such as files, network protocols, or image processing. Unlike JavaScript, which is typically used to handle text-based data, Node.js provides buffers to manage raw binary data. This article delves into what
4 min read
Node.js StreamsNode.js streams are a key part of handling I/O operations efficiently. They provide a way to read or write data continuously, allowing for efficient data processing, manipulation, and transfer.\Node.js StreamsThe stream module in Node.js provides an abstraction for working with streaming data. Strea
4 min read
Node.js Asynchronous Programming
Node.js NPM
NodeJS NPMNPM (Node Package Manager) is a package manager for NodeJS modules. It helps developers manage project dependencies, scripts, and third-party libraries. By installing NodeJS on your system, NPM is automatically installed, and ready to use.It is primarily used to manage packages or modulesâthese are
6 min read
Steps to Create and Publish NPM packagesIn this article, we will learn how to develop and publish your own npm package (also called an NPM module). There are many benefits of NPM packages, some of them are listed below: Reusable codeManaging code (using versioning)Sharing code The life-cycle of an npm package takes place like below: Modu
7 min read
Introduction to NPM scriptsNPM is a Node Package Manager. It is the world's largest Software Registry. This registry contains over 800,000 code packages. Many Open-source developers use npm to share software. Many organizations also use npm to manage private development. "npm scripts" are the entries in the scripts field of t
2 min read
Node.js package.jsonThe package.json file is the heart of Node.js system. It is the manifest file of any Node.js project and contains the metadata of the project. The package.json file is the essential part to understand, learn and work with the Node.js. It is the first step to learn about development in Node.js.What d
4 min read
What is package-lock.json ?package-lock.json is a file that is generated when we try to install the node. It is generated by the Node Package Manager(npm). package-lock.json will ensure that the same versions of packages are installed. It contains the name, dependencies, and locked version of the project. It will check that s
3 min read
Node.js Deployments & Communication
Node DebuggingDebugging is an essential part of software development that helps developers identify and fix errors. This ensures that the application runs smoothly without causing errors. NodeJS is the JavaScript runtime environment that provides various debugging tools for troubleshooting the application.What is
3 min read
How to Perform Testing in Node.js ?Testing is a method to check whether the functionality of an application is the same as expected or not. It helps to ensure that the output is the same as the required output. How Testing can be done in Node.js? There are various methods by which tasting can be done in Node.js, but one of the simple
2 min read
Unit Testing of Node.js ApplicationNode.js is a widely used javascript library based on Chrome's V8 JavaScript engine for developing server-side applications in web development. Unit Testing is a software testing method where individual units/components are tested in isolation. A unit can be described as the smallest testable part of
5 min read
NODE_ENV Variables and How to Use Them ?Introduction: NODE_ENV variables are environment variables that are made popularized by the express framework. The value of this type of variable can be set dynamically depending on the environment(i.e., development/production) the program is running on. The NODE_ENV works like a flag which indicate
2 min read
Difference Between Development and Production in Node.jsIn this article, we will explore the key differences between development and production environments in Node.js. Understanding these differences is crucial for deploying and managing Node.js applications effectively. IntroductionNode.js applications can behave differently depending on whether they a
3 min read
Best Security Practices in Node.jsThe security of an application is extremely important when we build a highly scalable and big project. So in this article, we are going to discuss some of the best practices that we need to follow in Node.js projects so that there are no security issues at a later point of time. In this article, we
4 min read
Deploying Node.js ApplicationsDeploying a NodeJS application can be a smooth process with the right tools and strategies. This article will guide you through the basics of deploying NodeJS applications.To show how to deploy a NodeJS app, we are first going to create a sample application for a better understanding of the process.
5 min read
How to Build a Microservices Architecture with NodeJSMicroservices architecture allows us to break down complex applications into smaller, independently deployable services. Node.js, with its non-blocking I/O and event-driven nature, is an excellent choice for building microservices. How to Build a Microservices Architecture with NodeJS?Microservices
3 min read
Node.js with WebAssemblyWebAssembly, often abbreviated as Wasm, is a cutting-edge technology that offers a high-performance assembly-like language capable of being compiled from various programming languages such as C/C++, Rust, and AssemblyScript. This technology is widely supported by major browsers including Chrome, Fir
3 min read
Resources & Tools
Node.js Web ServerA NodeJS web server is a server built using NodeJS to handle HTTP requests and responses. Unlike traditional web servers like Apache or Nginx, which are primarily designed to give static content, NodeJS web servers can handle both static and dynamic content while supporting real-time communication.
6 min read
Node Exercises, Practice Questions and SolutionsNode Exercise: Explore interactive quizzes, track progress, and enhance coding skills with our engaging portal. Ideal for beginners and experienced developers, Level up your Node proficiency at your own pace. Start coding now! #content-iframe { width: 100%; height: 500px;} @media (max-width: 768px)
4 min read
Node.js ProjectsNode.js is one of the most popular JavaScript runtime environments widely used in the software industry for projects in different domains like web applications, real-time chat applications, RESTful APIs, microservices, and more due to its high performance, scalability, non-blocking I/O, and many oth
9 min read
NodeJS Interview Questions and AnswersNodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read