codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🚂

Express.js

6 / 76 topics
4Routing in Express.js5Middleware Functions6Error Handling in Express.js15Creating Custom Middleware16Handling Asynchronous Operations in Middleware19Route Parameters in Express.js23Error-Handling Middleware
Tutorials/Express.js/Error Handling in Express.js
🚂Express.js

Error Handling in Express.js

Updated 2026-05-15
10 min read

Error Handling in Express.js

Introduction

In any web application, encountering errors is inevitable. Proper error handling is crucial to ensure a smooth user experience and maintain the stability of your application. In this section, we will explore best practices for handling errors in Express.js applications.

Error handling in Express.js can be done using middleware functions. 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. These functions can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware function.

Concept

Express.js provides several ways to handle errors:

  1. Error-handling Middleware: This is a special type of middleware that takes four arguments: err, req, res, and next. It must be defined after all other app.use() and routes calls.
  2. Built-in Error Handler: Express has a built-in error handler that catches errors that were not previously handled.
  3. Custom Error Handling: You can create custom error classes to handle specific types of errors.

Error-Handling Middleware

Error-handling middleware functions have four arguments: (err, req, res, next). The first argument is the error object. If you need to pass any data to the error handler, you can do so by attaching it to the req or res objects.

Here's an example of how to define and use error-handling middleware:

JavaScript
1app.use((err, req, res, next) => {
2console.error(err.stack);
3res.status(500).send('Something broke!');
4});

Built-in Error Handler

Express has a built-in error handler that is added at the end of all middleware functions. It sends an appropriate HTTP response based on the type of error.

If you have defined any custom error-handling middleware, it will override the built-in error handler.

Custom Error Handling

You can create custom error classes to handle specific types of errors. This makes your code more organized and easier to maintain.

Here's an example of how to define a custom error class:

JavaScript
1class ApiError extends Error {
2constructor(message, statusCode) {
3 super(message);
4 this.statusCode = statusCode;
5}
6}
7
8app.use((err, req, res, next) => {
9if (err instanceof ApiError) {
10 return res.status(err.statusCode).json({ message: err.message });
11}
12res.status(500).send('Something broke!');
13});

Examples

Let's look at some practical examples of error handling in Express.js.

Example 1: Handling Route Errors

In this example, we will create a route that throws an error if the user is not authorized to access it.

JavaScript
1app.get('/protected', (req, res) => {
2throw new ApiError('Unauthorized access', 403);
3});
4
5app.use((err, req, res, next) => {
6if (err instanceof ApiError) {
7 return res.status(err.statusCode).json({ message: err.message });
8}
9res.status(500).send('Something broke!');
10});

Example 2: Handling Async Errors

In Express.js, errors that occur in asynchronous functions are not automatically passed to the error-handling middleware. You need to handle them manually.

Here's an example of how to handle async errors:

JavaScript
1app.get('/async', async (req, res) => {
2try {
3 const result = await someAsyncFunction();
4 res.send(result);
5} catch (err) {
6 next(err);
7}
8});
9
10app.use((err, req, res, next) => {
11if (err instanceof ApiError) {
12 return res.status(err.statusCode).json({ message: err.message });
13}
14res.status(500).send('Something broke!');
15});

What's Next?

In the next section, we will explore how to use templates with Express.js. Templates allow you to generate HTML dynamically and make your application more dynamic.

Stay tuned for more tutorials on Express.js!


PreviousMiddleware FunctionsNext Using Templates with Express.js

Recommended Gear

Middleware FunctionsUsing Templates with Express.js