How to Handle API Errors in Express: Simple Error Middleware
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.
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'));
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.
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'));
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
next(err) to forward errors to the error handler.