Skip to main content
coding intermediate

Build Robust Error Handling Middleware

Generate production-ready error handling middleware for your backend API. Includes logging, status codes, and validation patterns.

Works with: chatgptclaudegemini

Prompt Template

I need you to create comprehensive error handling middleware for a [FRAMEWORK] backend application. The middleware should handle the following requirements: **Core Functionality:** - Catch and process all unhandled errors - Return appropriate HTTP status codes - Provide consistent error response format - Log errors with different severity levels - Handle both synchronous and asynchronous errors **Specific Requirements:** - Framework: [FRAMEWORK] - Error types to handle: [ERROR_TYPES] - Logging service: [LOGGING_SERVICE] - Environment: [ENVIRONMENT] - Include stack traces: [INCLUDE_STACK_TRACES] **Additional Features:** - Rate limiting for error responses - Error categorization (validation, authentication, server errors) - Custom error classes for different scenarios - Integration with error monitoring services - Sanitization of sensitive information in error responses Please include: 1. Main error handling middleware function 2. Custom error classes 3. Utility functions for error processing 4. Configuration options 5. Usage examples and integration instructions 6. Best practices for error logging and monitoring Ensure the code is production-ready, well-commented, and follows security best practices for error handling.

Variables to Customize

[FRAMEWORK]

The backend framework being used

Example: Express.js

[ERROR_TYPES]

Specific types of errors to handle

Example: validation errors, authentication errors, database errors, external API errors

[LOGGING_SERVICE]

The logging service or library to use

Example: Winston

[ENVIRONMENT]

The deployment environment

Example: production

[INCLUDE_STACK_TRACES]

Whether to include stack traces in responses

Example: only in development

Example Output

```javascript const winston = require('winston'); // Custom Error Classes class ValidationError extends Error { constructor(message, field) { super(message); this.name = 'ValidationError'; this.statusCode = 400; this.field = field; } } class AuthenticationError extends Error { constructor(message = 'Authentication failed') { super(message); this.name = 'AuthenticationError'; this.statusCode = 401; } } // Logger configuration const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.json() ), transports: [ new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.Console() ] }); // Main Error Handling Middleware const errorHandler = (err, req, res, next) => { let statusCode = err.statusCode || 500; let message = err.message || 'Internal Server Error'; // Log error with context logger.error({ message: err.message, stack: err.stack, url: req.url, method: req.method, ip: req.ip, userAgent: req.get('User-Agent') }); // Handle specific error types if (err.name === 'ValidationError') { statusCode = 400; } else if (err.name === 'CastError') { statusCode = 400; message = 'Invalid data format'; } // Sanitize error response const errorResponse = { success: false, error: { message, type: err.name || 'ServerError', timestamp: new Date().toISOString() } }; // Include stack trace only in development if (process.env.NODE_ENV === 'development') { errorResponse.error.stack = err.stack; } res.status(statusCode).json(errorResponse); }; module.exports = { errorHandler, ValidationError, AuthenticationError }; ```

Pro Tips for Best Results

  • Always log errors with sufficient context (request details, user info, timestamp) for debugging
  • Create specific error classes for different types of failures to handle them appropriately
  • Never expose sensitive information like database credentials or internal paths in error messages
  • Use different log levels (error, warn, info) to categorize the severity of issues
  • Test your error handling with various edge cases and malformed requests

Tags

Want 500+ Expert Prompts?

Get the Premium Prompt Pack — organized, tested, and ready to use.

Get it for $29

Related Prompts You Might Like