0
0
ExpressDebug / FixBeginner · 4 min read

How to Handle 500 Errors in Express: Simple Error Middleware

In Express, handle 500 errors by adding an error-handling middleware with four arguments: err, req, res, next. This middleware catches server errors and sends a proper response, preventing the app from crashing.
🔍

Why This Happens

A 500 Internal Server Error happens when your Express app encounters an unexpected problem, like a bug or an exception, but does not catch it properly. Without error handling, the app crashes or sends a generic error response.

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

app.get('/', (req, res) => {
  // This will cause an error but no handler catches it
  throw new Error('Something went wrong!');
});

app.listen(3000);
Output
Error: Something went wrong! at ... (stack trace) The server crashes or sends a default error response without details.
🔧

The Fix

Add an error-handling middleware at the end of your middleware stack. This middleware has four parameters: err, req, res, next. It catches errors like the thrown one and sends a 500 status with a friendly message.

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.stack);
  res.status(500).send('Internal Server Error. Please try again later.');
});

app.listen(3000);
Output
When visiting '/', the server responds with status 500 and message: 'Internal Server Error. Please try again later.' The server does not crash and logs the error stack in the console.
🛡️

Prevention

Always include error-handling middleware as the last middleware in your Express app. 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.

⚠️

Related Errors

Other common errors include 404 Not Found when routes are missing, and 400 Bad Request for invalid input. Use middleware to catch 404 errors and validate inputs to avoid these.

Key Takeaways

Always add error-handling middleware with four parameters to catch server errors.
Use res.status(500) to send a clear 500 Internal Server Error response.
Forward errors in async code using next(err) to trigger the error handler.
Log errors internally but avoid exposing sensitive details to users.
Include a 404 handler to catch missing routes and improve user experience.