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.

Example07
Loading editor…

βš™οΈ 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
Example08
Loading editor…

🧩 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