hmu.ai
Back to Builder Agents
Builder Agent

Hyper-Focused Error Handling Middleware Implementation for Freelance Developers

Stop doing this manually. Deploy an autonomous Builder agent to handle error handling middleware implementation entirely in the background.

Zero-Shot Command Setup

Generate Express.js error handling middleware for a Node.js API. Include centralized error logging with Winston, graceful shutdown, and distinct handling for 404, validation errors (Joi), and generic server errors.

Core Benefits & ROI

  • Ensures robust and consistent error management
  • Reduces boilerplate code for error handling
  • Improves API stability and user experience
  • Simplifies debugging with centralized logging
  • Accelerates development of resilient backends

Ecosystem Integration

This agent is a cornerstone of the 'Build' pillar, offering freelance developers a pre-built, robust foundation for error management in their backend applications. By generating sophisticated error-handling middleware, it ensures that applications are not only stable but also provide meaningful feedback and logging, which is crucial for maintenance and debugging. This capability accelerates the development of production-ready APIs, significantly reducing the time spent on common but critical infrastructure tasks and allowing developers to focus on unique business logic.

Sample Output

```javascript // src/middleware/errorHandler.js const winston = require('winston'); // Configure Winston logger const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.Console(), new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }), ], }); // Handle 404 Not Found errors const notFoundHandler = (req, res, next) => { const error = new Error(`Not Found - ${req.originalUrl}`); res.status(404); next(error); }; // Main error handling middleware const errorHandler = (err, req, res, next) => { let statusCode = res.statusCode === 200 ? 500 : res.statusCode; let message = err.message; let errors = err.errors; // For validation errors // Joi validation error handling if (err.isJoi) { statusCode = 400; // Bad Request message = 'Validation Error'; errors = err.details.map(detail => detail.message); } logger.error(`Status: ${statusCode}, Message: ${message}, Path: ${req.originalUrl}, Error: ${err.stack}`); res.status(statusCode).json({ message: message, errors: errors, stack: process.env.NODE_ENV === 'production' ? '🥞' : err.stack, // Hide stack in prod }); }; // Graceful shutdown example (integrate with server.js) const gracefulShutdown = (server) => { process.on('SIGTERM', () => { logger.info('SIGTERM signal received: closing HTTP server'); server.close(() => { logger.info('HTTP server closed'); process.exit(0); }); }); process.on('unhandledRejection', (reason, promise) => { logger.error('Unhandled Rejection at:', promise, 'reason:', reason); process.exit(1); // Exit with a failure code }); process.on('uncaughtException', (err) => { logger.error('Uncaught Exception:', err.message, err.stack); process.exit(1); // Exit with a failure code }); }; module.exports = { notFoundHandler, errorHandler, gracefulShutdown, logger }; // Example usage in app.js: // app.use(notFoundHandler); // app.use(errorHandler); // gracefulShutdown(serverInstance); ```

Frequently Asked Questions

How can I customize the logging output or integrate with other logging services?

The generated code uses Winston, which is highly configurable. You can modify the `winston.createLogger` configuration to change log levels, formats, and add transports for services like Loggly, Sentry, or custom file rotations as needed.

Does this middleware cover all possible error scenarios?

It provides a comprehensive base for common scenarios (404, validation, generic server errors) and graceful shutdown. For highly specific domain errors or third-party API errors, you might need to extend it with custom error classes and handlers tailored to your application's unique requirements.