0
0
ExpressDebug / FixBeginner · 4 min read

How to Handle API Errors in Express: Simple Error Middleware

In Express, handle API errors by creating an error-handling middleware function with four parameters: err, req, res, next. Use this middleware to catch errors and send proper HTTP status codes and messages to the client.
🔍

Why This Happens

When an error occurs in an Express route and you don't handle it properly, the server may crash or send a generic response. This happens because Express needs a special error-handling middleware to catch errors and respond gracefully.

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

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

app.listen(3000, () => console.log('Server running on port 3000'));
Output
Server crashes or sends a 500 Internal Server Error with no clear message.
🔧

The Fix

Add an error-handling middleware at the end of your middleware stack. This function has four parameters: err, req, res, next. It catches errors thrown in routes and sends a clear JSON response with the error message and status code.

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

app.get('/api/data', (req, res, next) => {
  try {
    throw new Error('Something went wrong!');
  } catch (err) {
    next(err); // Pass error to error handler
  }
});

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

app.listen(3000, () => console.log('Server running on port 3000'));
Output
{"error":"Something went wrong!"}
🛡️

Prevention

Always use error-handling middleware in Express apps to catch unexpected errors. Use try/catch blocks or next(err) in async routes. Validate inputs and handle promise rejections to avoid crashes.

Use tools like ESLint with rules for catching unhandled promises and errors early. Keep your error responses consistent and informative for easier debugging.

⚠️

Related Errors

Common related errors include unhandled promise rejections causing server crashes and sending incomplete responses. Fix these by using async error wrappers or libraries like express-async-errors to automatically forward errors to your error handler.

Key Takeaways

Use error-handling middleware with four parameters to catch and respond to errors in Express.
Always call next(err) to forward errors to the error handler.
Wrap async route code with try/catch or use async error handling helpers.
Validate inputs and handle promise rejections to prevent crashes.
Keep error responses clear and consistent for easier debugging.