How to Handle 500 Errors in Express: Simple Error Middleware
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.
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);
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.
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);
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
res.status(500) to send a clear 500 Internal Server Error response.next(err) to trigger the error handler.