Error Handling Middleware in Express.js
Error handling is a critical part of any backend application. In Express.js, error handling is managed using special middleware functions that catch and process errors during the request-response cycle.
Without proper error handling, your application may crash or return unclear responses to the client. Error middleware ensures that all errors are handled gracefully and consistently.
err, req, res, and next.
What is Error Handling Middleware?
Error handling middleware is a special type of middleware used to catch errors in your application. Unlike normal middleware, it has four parameters:
err– the error objectreq– the request objectres– the response objectnext– the next middleware function
Express identifies error middleware based on these four arguments.
Basic Error Middleware Example
In this example:
- The middleware catches any error passed using
next(err) - It sends a response with status code
500 - The error message is returned in JSON format
{ "error": "Something went wrong" }
How Errors Are Passed
In Express, errors are passed using the next() function.
When next(error) is called, Express skips normal middleware and directly moves to the error-handling middleware.
Handling Errors in Async Code
When using asynchronous code, errors should be handled properly using try-catch blocks.
Custom Error Responses
You can customize error responses based on different conditions:
Common Error Types
- 400: Bad Request (invalid input)
- 401: Unauthorized
- 404: Not Found
- 500: Internal Server Error
Handling 404 Errors
You can create middleware to handle routes that are not found:
Middleware Order Matters
Error-handling middleware should always be defined at the end of all routes and middleware.
If placed earlier, it may not catch all errors properly.
Best Practices
- Always use
next(err)to pass errors - Keep error responses consistent
- Do not expose sensitive information in errors
- Use proper HTTP status codes
- Handle async errors properly
Common Mistakes
- Forgetting to include all four parameters in error middleware
- Not calling
next(err) - Sending multiple responses
- Not handling async errors
Real-World Use Cases
- Handling API validation errors
- Managing authentication errors
- Logging server errors
- Returning user-friendly error messages
Conclusion
Error handling middleware is essential for building stable and production-ready Express.js applications. It ensures that errors are handled properly and users receive meaningful responses.
By implementing proper error handling, you can improve application reliability and debugging.

