Add Centralized Error Handling Middleware in Express
Use this AI prompt to create a global error-handling middleware for Express that formats error responses, logs issues, and prevents crashes in production.
🧠 What This Prompt Does
This AI prompt helps you implement a centralized error-handling middleware for Express.
It provides uniform error responses, logs issues for debugging, and prevents unhandled rejections from crashing your app.
💬 The Prompt
You are a backend engineer.
Generate a centralized error-handling middleware for Express.
Requirements:
- Catch all thrown or forwarded errors
- Log error message and stack trace
- Send structured JSON response
- Hide internal details in production
- Include example usage
🚀 Example Output (AI Generated)
// middleware/errorHandler.js
export const errorHandler = (err, req, res, next) => {
console.error('Error:', err.message);
const status = err.statusCode || 500;
const message =
process.env.NODE_ENV === 'production'
? 'Internal Server Error'
: err.message;
res.status(status).json({
success: false,
message,
...(process.env.NODE_ENV !== 'production' && { stack: err.stack }),
});
};
// Example usage:
import express from 'express';
import { errorHandler } from './middleware/errorHandler.js';
const app = express();
app.use('/api', routes);
app.use(errorHandler);
📘 When to Use This Prompt
- For consistent error responses in all APIs.
- When logging or debugging issues in production.
- To simplify try-catch logic across your app.
💡 Best Practices
- Always
next(err)in async routes to forward errors. - Avoid leaking sensitive data in error messages.
- Combine this with Winston or Pino for structured logging.
- Define custom error classes for known issues.
🏁 Summary
This prompt helps you build a robust error-handling system in Express — providing consistent responses and stable, maintainable backend behavior.
Where should I place the error-handling middleware?
Always define it after all route handlers in your Express app, as the last middleware.
How can I handle async errors automatically?
Use try-catch blocks or async wrappers around route handlers to forward errors to the global handler.
Can I send different messages in production vs development?
Yes. Hide stack traces in production by checking `process.env.NODE_ENV`.
Advertisement