Error-Handling Middleware in Express.js
Error-handling middleware helps an Express.js application handle errors in a centralized and organized way.
During application execution, errors can occur because of invalid input, database failures, missing resources, or unexpected application problems. Instead of writing separate error-handling logic in every route, we can use error-handling middleware.
Express identifies error-handling middleware by its four
parameters: err, req, res,
and next. It can generate a suitable response and
prevent internal error details from being unnecessarily exposed
to clients.
1. What Is Error-Handling Middleware?
Error-handling middleware is a special middleware function used to handle errors that occur while processing requests.
Unlike regular middleware, it receives four parameters:
- err: Contains the error information.
- req: Contains information about the request.
- res: Is used to send a response to the client.
- next: Passes the error to another error handler when needed.
function errorHandler(err, req, res, next) {
console.error(err.stack);
res.status(500).json({
message: 'Something went wrong!'
});
}
In this example, the middleware logs the error on the server and sends a generic HTTP 500 response to the client.
2. Why Do We Need Error-Handling Middleware?
Without centralized error handling, applications can become difficult to maintain because every route may handle failures differently.
| Error Situation | Example | Possible Response |
|---|---|---|
| Invalid Input | A required field is missing. | 400 Bad Request |
| Missing Resource | A requested product does not exist. | 404 Not Found |
| Authentication Failure | Valid authentication credentials are missing. | 401 Unauthorized |
| Database Failure | The database operation fails. | 500 Internal Server Error |
| Unexpected Error | An unhandled application problem occurs. | 500 Internal Server Error |
The status code should describe the actual failure. A missing resource is generally a 404 error, while unexpected server-side failures generally require a 500 response.
3. Diagram 1: How Error-Handling Middleware Works
The diagram below explains how a request can produce an error and how Express can pass that error to an error handler.
Client Request
Browser or API client sends a request
Route Handler
Processes the request
Error Occurs
An operation fails or detects a problem
next(err)
Passes control to error-handling middleware
Error-Handling Middleware
Logs the error and prepares a response
Error Response
Client receives an appropriate status code
Step-by-step explanation:
- The client sends a request to the Express application.
- A route handler starts processing the request.
- An error occurs during the operation.
- The route passes the error using
next(err), or a supported error-handling mechanism forwards it. - Express skips regular middleware and looks for the next error handler.
- The error handler sends an appropriate response.
4. Creating Your First Error Handler
Let us create a simple application that deliberately forwards an error to the error-handling middleware.
Step 1: Create app.js
const express = require('express');
const app = express();
// Normal route
app.get('/', (req, res) => {
res.send('Welcome to Express.js');
});
// Route that generates an error
app.get('/error', (req, res, next) => {
const err = new Error('Something went wrong');
next(err);
});
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.message);
res.status(500).json({
message: 'Internal Server Error'
});
});
// Start server
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Step 2: Install Express.js
npm init -y
npm install express
Step 3: Run the application
node app.js
Step 4: Open the error URL
http://localhost:3000/error
Example terminal output:
Server running on port 3000
Something went wrong
Browser JSON response:
{
"message": "Internal Server Error"
}
The route calls next(err). Express forwards the
error to the registered error handler, which logs the message
and sends a JSON response with status code 500.
5. Handling a 404 Not Found Error
A 404 error means that the server could not find a matching resource or route. It is different from an unexpected server error, which is generally represented by status code 500.
A simple 404 handler can be registered after all application routes. It sends a response when no earlier route has handled the request.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Home Page');
});
// 404 handler - register after routes
app.use((req, res) => {
res.status(404).json({
message: 'Route not found'
});
});
// Error handler - register after the 404 handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
message: 'Internal Server Error'
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Try this URL:
http://localhost:3000/unknown
Example response:
{
"message": "Route not found"
}
6. Diagram 2: Difference Between 404 and 500 Errors
A missing route and an unexpected application error need different handling. The diagram illustrates the two common paths.
Incoming Request
Client requests a URL
Route Processing
Express tries to process the request
No Matching Route
Request is not handled by a route
Regular 404 middleware responds
Application Error
Route forwards an error
Error-handling middleware responds
Explanation:
- 404: The requested route or resource was not found.
- 500: An unexpected server-side error occurred.
- The 404 handler usually sends a response without calling
next(). - The error handler receives errors forwarded through
next(err)or supported error propagation.
7. Handling Errors in Asynchronous Code
Asynchronous operations, such as database queries or external API calls, may fail. Those errors must be forwarded to Express so that the error handler can process them.
The following example uses async and await.
Express 5 automatically forwards rejected promises returned by
route handlers. In Express 4, wrap the asynchronous logic in
try...catch and call next(err).
const express = require('express');
const app = express();
app.get('/data', async (req, res, next) => {
try {
// Simulate a failed asynchronous operation
throw new Error('Unable to load data');
} catch (err) {
next(err);
}
});
app.use((err, req, res, next) => {
console.error(err.message);
res.status(500).json({
message: 'Unable to process your request'
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Here, the error is caught and passed to
next(err). The error-handling middleware then
sends a safe response to the client.
8. Best Practices for Error Handling
| Practice | Why It Matters |
|---|---|
| Register error handlers after routes | Allows errors from earlier middleware and routes to reach the handler. |
| Use meaningful status codes | Helps clients understand the kind of failure. |
| Log errors on the server | Helps developers investigate and fix problems. |
| Send safe error messages | Prevents exposing sensitive internal information. |
| Forward asynchronous errors | Ensures failures reach Express error handling. |
| Avoid sending multiple responses | Prevents response errors after headers have been sent. |
Important Points to Remember
- Error-handling middleware has four parameters:
err, req, res, next. - Use
next(err)to forward an error. - Register the error handler after the routes it should handle.
- A 404 handler is generally regular middleware, not error-handling middleware.
- Use 404 for missing routes and appropriate 500 responses for unexpected server failures.
- Forward asynchronous errors to Express.
- Never expose sensitive internal details to clients.
- Do not send a second response after a response has already been sent.
Summary
Error-handling middleware provides a centralized way to handle application errors in Express.js. It receives the error, request, response, and next function, allowing the application to log failures and send suitable responses.
By forwarding errors correctly, distinguishing 404 responses from server errors, and keeping internal details private, developers can make Express.js applications easier to debug and more reliable.