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
awaitwithoutasync - 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
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'); });
⚙️ Built-in Middleware in Express
Express provides these built-in middlewares:
express.json()— Parse incoming JSON dataexpress.urlencoded()— Parse form-dataexpress.static()— Serve static files
Express.js Server
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"); });
🧩 Popular Third-Party Middleware
Useful third-party middleware from npm:
| Middleware | Use |
|---|---|
| cookie-parser | Parse cookies |
| helmet | Security headers |
| morgan | HTTP request logger |
| body-parser | Parse request bodies |
| cors | Enable CORS |
| multer | Handle file uploads |
| express-session | Session handling |
| compression | Gzip response compression |
📘 Summary for Beginners
| Type | Description |
|---|---|
| Application-Level | Added using app.use() |
| Router-Level | Applied to specific router objects |
| Error-Handling | Middleware with 4 parameters |
| Built-in | Provided by Express (json, static) |
| Third-Party | External npm packages |