0
0
ExpressDebug / FixBeginner · 3 min read

How to Handle Errors in Express: Simple Guide with Examples

In Express, handle errors by creating an error-handling middleware with four parameters: err, req, res, next. Place this middleware after all routes to catch and respond to errors gracefully.
🔍

Why This Happens

When an error occurs in an Express route but there is no error-handling middleware, the server may crash or send incomplete responses. This happens because Express does not know how to handle the error properly without a dedicated handler.

javascript
import express from 'express';
const app = express();

app.get('/', (req, res) => {
  throw new Error('Something went wrong!');
});

app.listen(3000, () => console.log('Server running on port 3000'));
Output
Error: Something went wrong! at ... (stack trace) Server crashes or hangs without proper error response.
🔧

The Fix

Add an error-handling middleware function with four parameters: err, req, res, next. This middleware catches errors thrown in routes and sends a proper response without crashing the server.

javascript
import express from 'express';
const app = express();

app.get('/', (req, res) => {
  throw new Error('Something went wrong!');
});

// Error-handling middleware
app.use((err, req, res, next) => {
  console.error(err.message);
  res.status(500).send('Internal Server Error: ' + err.message);
});

app.listen(3000, () => console.log('Server running on port 3000'));
Output
When visiting '/', the server responds with status 500 and message: 'Internal Server Error: Something went wrong!' without crashing.
🛡️

Prevention

Always include an error-handling middleware at the end of your middleware stack to catch errors. Use try/catch blocks or async/await with next(err) to forward errors. Use logging to track errors and avoid exposing sensitive info to users.

Linting tools like ESLint can help enforce error handling patterns.

⚠️

Related Errors

Common related errors include unhandled promise rejections and missing next(err) calls in async routes. To fix, always call next(err) inside catch blocks or use middleware like express-async-errors to handle async errors automatically.

Key Takeaways

Use error-handling middleware with four parameters to catch errors in Express.
Place error middleware after all routes to handle errors globally.
Forward errors in async code using next(err) or try/catch blocks.
Log errors for debugging but avoid exposing sensitive details to users.
Use linting and middleware helpers to enforce consistent error handling.