Express Error Handling
🎯 Introduction
Things go wrong: a user visits a nonexistent URL, a record cannot be found, or code throws an exception. By the end of this article, you will be able to add 404 handling and centralized error-handling middleware so unexpected situations produce appropriate responses instead of bringing down the service.
🧱 Why Centralize Error Handling?
Without custom handling, an exception thrown in a route makes Express return its default HTML error page, which may even expose a stack trace to the client. This is unhelpful for users and can reveal internal server details.
Our goal is that clients receive JSON errors in a consistent format, wherever an error occurs. The frontend can then handle them centrally, for example by showing a notification.
🛠 Handle 404: Endpoint Not Found
When no route matches a request, Express returns HTML by default. A common alternative is to register fallback middleware after all routes:
import express from 'express';
const app = express();
app.get('/', (req, res) => {
res.send('Home page');
});
// 404 fallback: runs after all routes if none has handled the request
app.use((req, res) => {
res.status(404).json({ code: 404, message: 'Endpoint not found' });
});
app.listen(3000);
Visiting an unmatched URL such as /abc now returns a JSON response with status 404.
🧱 Error-handling Middleware: Four Parameters
Regular middleware has three parameters. Error-handling middleware requires four, with the error object err first:
// Error-handling middleware: Express identifies it by its four parameters
app.use((err, req, res, next) => {
console.error('Error:', err.message);
res.status(500).json({ code: 500, message: 'Something went wrong. Please try again later.' });
});
Express distinguishes these middleware types by their parameter count. If you omit next, the function becomes regular middleware and never receives errors. Register it after all routes too.
When a route encounters an error, pass it to this middleware with next(err):
app.get('/users/:id', (req, res, next) => {
const user = null; // Assume the database query found no user
if (!user) {
// Forward the error to the error-handling middleware
return next(new Error('User not found'));
}
res.json(user);
});
✨ Express 5: Automatic Asynchronous Error Forwarding
What happens when an async route handler throws? This is an important difference between Express 4 and 5.
Express 4: Errors thrown in async functions are not forwarded automatically. You must use try/catch and call next(err) yourself, or the process may crash. This was a well-known pitfall in Express 4.
Express 5: The framework automatically forwards errors from async route handlers and rejections from returned promises to error-handling middleware. You do not need to call next(err) manually:
app.get('/users', async (req, res) => {
// Express 5 automatically forwards this error to the error-handling middleware
throw new Error('Database query failed');
});
With the error-handling middleware above, visiting /users returns the consistent JSON error response with status 500, and the server keeps running.
async handlers. It does not catch errors thrown later in callbacks such as setTimeout. In those cases, use try/catch inside the callback and call next(err). Writing routes as async functions covers most everyday asynchronous operations.🛠 Use a Consistent Error Response Format
Putting everything together, define a shared response convention for the project:
- Success:
{ code: 0, data: data } - Failure:
{ code: errorCode, message: 'Error message' }
import express from 'express';
const app = express();
app.use(express.json());
app.get('/users/:id', async (req, res) => {
const id = Number(req.params.id);
if (id !== 1) {
// Throw an error for centralized handling
throw new Error('User not found');
}
res.json({ code: 0, data: { id: 1, name: 'Ming' } });
});
// 404 fallback
app.use((req, res) => {
res.status(404).json({ code: 404, message: 'Endpoint not found' });
});
// Centralized error handling
app.use((err, req, res, next) => {
console.error('Error:', err.message);
res.status(500).json({ code: 500, message: err.message });
});
app.listen(3000);
With this structure, routes can simply throw errors. The error-handling middleware controls the response format, and the frontend can parse responses using the same convention.
❓ Questions and Answers
Q1: Can I remove next if the error-handling middleware does not use it?
No. Express identifies error-handling middleware by its four parameters. Removing next makes it regular middleware, so it will not receive errors.
Q2: How do next() and next(err) differ?
next() passes control to the next regular middleware or route. next(err) reports an error: Express skips subsequent regular middleware and routes and goes to error-handling middleware.
Q3: Does throwing an error crash the server?
As long as the error reaches error-handling middleware, the server continues handling other requests. Uncaught errors in asynchronous callbacks, such as exceptions inside setTimeout, can still terminate the process in Express 5. Handle those yourself with try/catch.
Q4: Can I combine 404 and 500 handling in one middleware function?
It is better to keep them separate. A 404 means no route matched; error handling deals with a failure during request processing. They are triggered differently. Separate handlers keep responsibilities clear and follow common practice.
🧪 Exercise
Add error handling to a /divide endpoint. Read query parameters a and b and return a / b. If b is 0, throw an error and let the error-handling middleware return JSON in the shared error format.
import express from 'express';
const app = express();
app.get('/divide', async (req, res) => {
// Write your code here
});
// Write the 404 fallback and error-handling middleware here
app.listen(3000);
🎉 You now know how to handle errors in Express! Next, we will put everything together to build a complete RESTful API for users.
