Nearby lessons

14 of 14

⚠️ Error Handling Middleware in Express JS | Types of Errors & Middleware Structure

📌 What is Error Handling?

💡 Understanding Error Handling in Express.js

Error handling is an essential part of building stable and secure applications. Express.js provides a special type of middleware that catches and manages errors in a centralized place.

🔍 Two Types of Errors

🔍 Two Types of Errors

  • Operational Errors — predictable issues that may occur in real-world usage.
  • Programming Errors — bugs introduced by developers in code.

🔧 1. Operational Errors

Operational errors are predictable issues that will happen at some point in the future. These errors are known as runtime errors that you can handle in advance.

📝 Examples:

  • Accessing an invalid route
  • Submitting invalid data
  • Server connection failure
  • Request timeout

🐞 2. Programming Errors

Programming errors are mistakes made by developers. These are bugs inside the code and are usually not predictable.

📝 Examples:

  • Trying to access a property of undefined
  • Using await without async
  • Passing wrong data types to functions

⚙️ What is Error Handling Middleware?

Express.js uses a special middleware with four parameters to catch errors: (err, req, res, next).

This function is used to log, format, and send error responses from one place.

📌 Syntax of Error Handling Middleware

function errorHandler(err, req, res, next) {
    // Handle the error
}
        

📄 Example: Error Handling Middleware

Complete working example demonstrating routes, 404 page, and error handling.

Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();

// Normal routes
app.get('/', (req, res) => {
    res.send('Home Page');
});

app.get('/about', (req, res) => {
    // Intentional mistake to trigger error
    res.sen('About Page'); // Wrong method name
});

// 404 Middleware - Handles undefined routes
app.use((req, res) => {
    res.status(404).send('<h1>404 Not Found</h1>');
});

// Error-handling middleware (must have 4 parameters)
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

// Start server
app.listen(8080, () => {
    console.log('Server is running at http://localhost:8080');
});

Browser Output
Server logs

⚙️ Built-in Middleware in Express

Express provides these built-in middlewares:

  • express.json() — Parse incoming JSON data
  • express.urlencoded() — Parse form-data
  • express.static() — Serve static files
Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();

// Built-in middleware examples in ExpressJS

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public')); // Static folder

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});

Browser Output
Server logs

🧩 Popular Third-Party Middleware

Useful third-party middleware from npm:

MiddlewareUse
cookie-parserParse cookies
helmetSecurity headers
morganHTTP request logger
body-parserParse request bodies
corsEnable CORS
multerHandle file uploads
express-sessionSession handling
compressionGzip response compression

📘 Summary for Beginners

TypeDescription
Application-LevelAdded using app.use()
Router-LevelApplied to specific router objects
Error-HandlingMiddleware with 4 parameters
Built-inProvided by Express (json, static)
Third-PartyExternal npm packages

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Course Complete!