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.
βοΈ 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
π§© 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 |